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`](crate::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    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1542        self.transaction_depth += 1;
1543        if self.was_dirty_before_starting_transaction.is_none() {
1544            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
1545        }
1546        self.text.start_transaction_at(now)
1547    }
1548
1549    /// Terminates the current transaction, if this is the outermost transaction.
1550    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1551        self.end_transaction_at(Instant::now(), cx)
1552    }
1553
1554    /// Terminates the current transaction, providing the current time. Subsequent transactions
1555    /// that occur within a short period of time will be grouped together. This
1556    /// is controlled by the buffer's undo grouping duration.
1557    pub fn end_transaction_at(
1558        &mut self,
1559        now: Instant,
1560        cx: &mut ModelContext<Self>,
1561    ) -> Option<TransactionId> {
1562        assert!(self.transaction_depth > 0);
1563        self.transaction_depth -= 1;
1564        let was_dirty = if self.transaction_depth == 0 {
1565            self.was_dirty_before_starting_transaction.take().unwrap()
1566        } else {
1567            false
1568        };
1569        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1570            self.did_edit(&start_version, was_dirty, cx);
1571            Some(transaction_id)
1572        } else {
1573            None
1574        }
1575    }
1576
1577    /// Manually add a transaction to the buffer's undo history.
1578    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1579        self.text.push_transaction(transaction, now);
1580    }
1581
1582    /// Prevent the last transaction from being grouped with any subsequent transactions,
1583    /// even if they occur with the buffer's undo grouping duration.
1584    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1585        self.text.finalize_last_transaction()
1586    }
1587
1588    /// Manually group all changes since a given transaction.
1589    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
1590        self.text.group_until_transaction(transaction_id);
1591    }
1592
1593    /// Manually remove a transaction from the buffer's undo history
1594    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1595        self.text.forget_transaction(transaction_id);
1596    }
1597
1598    /// Manually merge two adjacent transactions in the buffer's undo history.
1599    pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
1600        self.text.merge_transactions(transaction, destination);
1601    }
1602
1603    /// Waits for the buffer to receive operations with the given timestamps.
1604    pub fn wait_for_edits(
1605        &mut self,
1606        edit_ids: impl IntoIterator<Item = clock::Lamport>,
1607    ) -> impl Future<Output = Result<()>> {
1608        self.text.wait_for_edits(edit_ids)
1609    }
1610
1611    /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
1612    pub fn wait_for_anchors(
1613        &mut self,
1614        anchors: impl IntoIterator<Item = Anchor>,
1615    ) -> impl 'static + Future<Output = Result<()>> {
1616        self.text.wait_for_anchors(anchors)
1617    }
1618
1619    /// Waits for the buffer to receive operations up to the given version.
1620    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
1621        self.text.wait_for_version(version)
1622    }
1623
1624    /// Forces all futures returned by [`Buffer::wait_for_version`], [`Buffer::wait_for_edits`], or
1625    /// [`Buffer::wait_for_version`] to resolve with an error.
1626    pub fn give_up_waiting(&mut self) {
1627        self.text.give_up_waiting();
1628    }
1629
1630    /// Stores a set of selections that should be broadcasted to all of the buffer's replicas.
1631    pub fn set_active_selections(
1632        &mut self,
1633        selections: Arc<[Selection<Anchor>]>,
1634        line_mode: bool,
1635        cursor_shape: CursorShape,
1636        cx: &mut ModelContext<Self>,
1637    ) {
1638        let lamport_timestamp = self.text.lamport_clock.tick();
1639        self.remote_selections.insert(
1640            self.text.replica_id(),
1641            SelectionSet {
1642                selections: selections.clone(),
1643                lamport_timestamp,
1644                line_mode,
1645                cursor_shape,
1646            },
1647        );
1648        self.send_operation(
1649            Operation::UpdateSelections {
1650                selections,
1651                line_mode,
1652                lamport_timestamp,
1653                cursor_shape,
1654            },
1655            cx,
1656        );
1657    }
1658
1659    /// Clears the selections, so that other replicas of the buffer do not see any selections for
1660    /// this replica.
1661    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1662        if self
1663            .remote_selections
1664            .get(&self.text.replica_id())
1665            .map_or(true, |set| !set.selections.is_empty())
1666        {
1667            self.set_active_selections(Arc::from([]), false, Default::default(), cx);
1668        }
1669    }
1670
1671    /// Replaces the buffer's entire text.
1672    pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Lamport>
1673    where
1674        T: Into<Arc<str>>,
1675    {
1676        self.autoindent_requests.clear();
1677        self.edit([(0..self.len(), text)], None, cx)
1678    }
1679
1680    /// Applies the given edits to the buffer. Each edit is specified as a range of text to
1681    /// delete, and a string of text to insert at that location.
1682    ///
1683    /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
1684    /// request for the edited ranges, which will be processed when the buffer finishes
1685    /// parsing.
1686    ///
1687    /// Parsing takes place at the end of a transaction, and may compute synchronously
1688    /// or asynchronously, depending on the changes.
1689    pub fn edit<I, S, T>(
1690        &mut self,
1691        edits_iter: I,
1692        autoindent_mode: Option<AutoindentMode>,
1693        cx: &mut ModelContext<Self>,
1694    ) -> Option<clock::Lamport>
1695    where
1696        I: IntoIterator<Item = (Range<S>, T)>,
1697        S: ToOffset,
1698        T: Into<Arc<str>>,
1699    {
1700        // Skip invalid edits and coalesce contiguous ones.
1701        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1702        for (range, new_text) in edits_iter {
1703            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1704            if range.start > range.end {
1705                mem::swap(&mut range.start, &mut range.end);
1706            }
1707            let new_text = new_text.into();
1708            if !new_text.is_empty() || !range.is_empty() {
1709                if let Some((prev_range, prev_text)) = edits.last_mut() {
1710                    if prev_range.end >= range.start {
1711                        prev_range.end = cmp::max(prev_range.end, range.end);
1712                        *prev_text = format!("{prev_text}{new_text}").into();
1713                    } else {
1714                        edits.push((range, new_text));
1715                    }
1716                } else {
1717                    edits.push((range, new_text));
1718                }
1719            }
1720        }
1721        if edits.is_empty() {
1722            return None;
1723        }
1724
1725        self.start_transaction();
1726        self.pending_autoindent.take();
1727        let autoindent_request = autoindent_mode
1728            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
1729
1730        let edit_operation = self.text.edit(edits.iter().cloned());
1731        let edit_id = edit_operation.timestamp();
1732
1733        if let Some((before_edit, mode)) = autoindent_request {
1734            let mut delta = 0isize;
1735            let entries = edits
1736                .into_iter()
1737                .enumerate()
1738                .zip(&edit_operation.as_edit().unwrap().new_text)
1739                .map(|((ix, (range, _)), new_text)| {
1740                    let new_text_length = new_text.len();
1741                    let old_start = range.start.to_point(&before_edit);
1742                    let new_start = (delta + range.start as isize) as usize;
1743                    delta += new_text_length as isize - (range.end as isize - range.start as isize);
1744
1745                    let mut range_of_insertion_to_indent = 0..new_text_length;
1746                    let mut first_line_is_new = false;
1747                    let mut original_indent_column = None;
1748
1749                    // When inserting an entire line at the beginning of an existing line,
1750                    // treat the insertion as new.
1751                    if new_text.contains('\n')
1752                        && old_start.column <= before_edit.indent_size_for_line(old_start.row).len
1753                    {
1754                        first_line_is_new = true;
1755                    }
1756
1757                    // When inserting text starting with a newline, avoid auto-indenting the
1758                    // previous line.
1759                    if new_text.starts_with('\n') {
1760                        range_of_insertion_to_indent.start += 1;
1761                        first_line_is_new = true;
1762                    }
1763
1764                    // Avoid auto-indenting after the insertion.
1765                    if let AutoindentMode::Block {
1766                        original_indent_columns,
1767                    } = &mode
1768                    {
1769                        original_indent_column =
1770                            Some(original_indent_columns.get(ix).copied().unwrap_or_else(|| {
1771                                indent_size_for_text(
1772                                    new_text[range_of_insertion_to_indent.clone()].chars(),
1773                                )
1774                                .len
1775                            }));
1776                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
1777                            range_of_insertion_to_indent.end -= 1;
1778                        }
1779                    }
1780
1781                    AutoindentRequestEntry {
1782                        first_line_is_new,
1783                        original_indent_column,
1784                        indent_size: before_edit.language_indent_size_at(range.start, cx),
1785                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
1786                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
1787                    }
1788                })
1789                .collect();
1790
1791            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1792                before_edit,
1793                entries,
1794                is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
1795            }));
1796        }
1797
1798        self.end_transaction(cx);
1799        self.send_operation(Operation::Buffer(edit_operation), cx);
1800        Some(edit_id)
1801    }
1802
1803    fn did_edit(
1804        &mut self,
1805        old_version: &clock::Global,
1806        was_dirty: bool,
1807        cx: &mut ModelContext<Self>,
1808    ) {
1809        if self.edits_since::<usize>(old_version).next().is_none() {
1810            return;
1811        }
1812
1813        self.reparse(cx);
1814
1815        cx.emit(Event::Edited);
1816        if was_dirty != self.is_dirty() {
1817            cx.emit(Event::DirtyChanged);
1818        }
1819        cx.notify();
1820    }
1821
1822    /// Applies the given remote operations to the buffer.
1823    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1824        &mut self,
1825        ops: I,
1826        cx: &mut ModelContext<Self>,
1827    ) -> Result<()> {
1828        self.pending_autoindent.take();
1829        let was_dirty = self.is_dirty();
1830        let old_version = self.version.clone();
1831        let mut deferred_ops = Vec::new();
1832        let buffer_ops = ops
1833            .into_iter()
1834            .filter_map(|op| match op {
1835                Operation::Buffer(op) => Some(op),
1836                _ => {
1837                    if self.can_apply_op(&op) {
1838                        self.apply_op(op, cx);
1839                    } else {
1840                        deferred_ops.push(op);
1841                    }
1842                    None
1843                }
1844            })
1845            .collect::<Vec<_>>();
1846        self.text.apply_ops(buffer_ops)?;
1847        self.deferred_ops.insert(deferred_ops);
1848        self.flush_deferred_ops(cx);
1849        self.did_edit(&old_version, was_dirty, cx);
1850        // Notify independently of whether the buffer was edited as the operations could include a
1851        // selection update.
1852        cx.notify();
1853        Ok(())
1854    }
1855
1856    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1857        let mut deferred_ops = Vec::new();
1858        for op in self.deferred_ops.drain().iter().cloned() {
1859            if self.can_apply_op(&op) {
1860                self.apply_op(op, cx);
1861            } else {
1862                deferred_ops.push(op);
1863            }
1864        }
1865        self.deferred_ops.insert(deferred_ops);
1866    }
1867
1868    fn can_apply_op(&self, operation: &Operation) -> bool {
1869        match operation {
1870            Operation::Buffer(_) => {
1871                unreachable!("buffer operations should never be applied at this layer")
1872            }
1873            Operation::UpdateDiagnostics {
1874                diagnostics: diagnostic_set,
1875                ..
1876            } => diagnostic_set.iter().all(|diagnostic| {
1877                self.text.can_resolve(&diagnostic.range.start)
1878                    && self.text.can_resolve(&diagnostic.range.end)
1879            }),
1880            Operation::UpdateSelections { selections, .. } => selections
1881                .iter()
1882                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1883            Operation::UpdateCompletionTriggers { .. } => true,
1884        }
1885    }
1886
1887    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1888        match operation {
1889            Operation::Buffer(_) => {
1890                unreachable!("buffer operations should never be applied at this layer")
1891            }
1892            Operation::UpdateDiagnostics {
1893                server_id,
1894                diagnostics: diagnostic_set,
1895                lamport_timestamp,
1896            } => {
1897                let snapshot = self.snapshot();
1898                self.apply_diagnostic_update(
1899                    server_id,
1900                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1901                    lamport_timestamp,
1902                    cx,
1903                );
1904            }
1905            Operation::UpdateSelections {
1906                selections,
1907                lamport_timestamp,
1908                line_mode,
1909                cursor_shape,
1910            } => {
1911                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
1912                    if set.lamport_timestamp > lamport_timestamp {
1913                        return;
1914                    }
1915                }
1916
1917                self.remote_selections.insert(
1918                    lamport_timestamp.replica_id,
1919                    SelectionSet {
1920                        selections,
1921                        lamport_timestamp,
1922                        line_mode,
1923                        cursor_shape,
1924                    },
1925                );
1926                self.text.lamport_clock.observe(lamport_timestamp);
1927                self.selections_update_count += 1;
1928            }
1929            Operation::UpdateCompletionTriggers {
1930                triggers,
1931                lamport_timestamp,
1932            } => {
1933                self.completion_triggers = triggers;
1934                self.text.lamport_clock.observe(lamport_timestamp);
1935            }
1936        }
1937    }
1938
1939    fn apply_diagnostic_update(
1940        &mut self,
1941        server_id: LanguageServerId,
1942        diagnostics: DiagnosticSet,
1943        lamport_timestamp: clock::Lamport,
1944        cx: &mut ModelContext<Self>,
1945    ) {
1946        if lamport_timestamp > self.diagnostics_timestamp {
1947            let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
1948            if diagnostics.len() == 0 {
1949                if let Ok(ix) = ix {
1950                    self.diagnostics.remove(ix);
1951                }
1952            } else {
1953                match ix {
1954                    Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
1955                    Ok(ix) => self.diagnostics[ix].1 = diagnostics,
1956                };
1957            }
1958            self.diagnostics_timestamp = lamport_timestamp;
1959            self.diagnostics_update_count += 1;
1960            self.text.lamport_clock.observe(lamport_timestamp);
1961            cx.notify();
1962            cx.emit(Event::DiagnosticsUpdated);
1963        }
1964    }
1965
1966    fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1967        cx.emit(Event::Operation(operation));
1968    }
1969
1970    /// Removes the selections for a given peer.
1971    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1972        self.remote_selections.remove(&replica_id);
1973        cx.notify();
1974    }
1975
1976    /// Undoes the most recent transaction.
1977    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1978        let was_dirty = self.is_dirty();
1979        let old_version = self.version.clone();
1980
1981        if let Some((transaction_id, operation)) = self.text.undo() {
1982            self.send_operation(Operation::Buffer(operation), cx);
1983            self.did_edit(&old_version, was_dirty, cx);
1984            Some(transaction_id)
1985        } else {
1986            None
1987        }
1988    }
1989
1990    /// Manually undoes a specific transaction in the buffer's undo history.
1991    pub fn undo_transaction(
1992        &mut self,
1993        transaction_id: TransactionId,
1994        cx: &mut ModelContext<Self>,
1995    ) -> bool {
1996        let was_dirty = self.is_dirty();
1997        let old_version = self.version.clone();
1998        if let Some(operation) = self.text.undo_transaction(transaction_id) {
1999            self.send_operation(Operation::Buffer(operation), cx);
2000            self.did_edit(&old_version, was_dirty, cx);
2001            true
2002        } else {
2003            false
2004        }
2005    }
2006
2007    /// Manually undoes all changes after a given transaction in the buffer's undo history.
2008    pub fn undo_to_transaction(
2009        &mut self,
2010        transaction_id: TransactionId,
2011        cx: &mut ModelContext<Self>,
2012    ) -> bool {
2013        let was_dirty = self.is_dirty();
2014        let old_version = self.version.clone();
2015
2016        let operations = self.text.undo_to_transaction(transaction_id);
2017        let undone = !operations.is_empty();
2018        for operation in operations {
2019            self.send_operation(Operation::Buffer(operation), cx);
2020        }
2021        if undone {
2022            self.did_edit(&old_version, was_dirty, cx)
2023        }
2024        undone
2025    }
2026
2027    /// Manually redoes a specific transaction in the buffer's redo history.
2028    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
2029        let was_dirty = self.is_dirty();
2030        let old_version = self.version.clone();
2031
2032        if let Some((transaction_id, operation)) = self.text.redo() {
2033            self.send_operation(Operation::Buffer(operation), cx);
2034            self.did_edit(&old_version, was_dirty, cx);
2035            Some(transaction_id)
2036        } else {
2037            None
2038        }
2039    }
2040
2041    /// Manually undoes all changes until a given transaction in the buffer's redo history.
2042    pub fn redo_to_transaction(
2043        &mut self,
2044        transaction_id: TransactionId,
2045        cx: &mut ModelContext<Self>,
2046    ) -> bool {
2047        let was_dirty = self.is_dirty();
2048        let old_version = self.version.clone();
2049
2050        let operations = self.text.redo_to_transaction(transaction_id);
2051        let redone = !operations.is_empty();
2052        for operation in operations {
2053            self.send_operation(Operation::Buffer(operation), cx);
2054        }
2055        if redone {
2056            self.did_edit(&old_version, was_dirty, cx)
2057        }
2058        redone
2059    }
2060
2061    /// Override current completion triggers with the user-provided completion triggers.
2062    pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
2063        self.completion_triggers = triggers.clone();
2064        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2065        self.send_operation(
2066            Operation::UpdateCompletionTriggers {
2067                triggers,
2068                lamport_timestamp: self.completion_triggers_timestamp,
2069            },
2070            cx,
2071        );
2072        cx.notify();
2073    }
2074
2075    /// Returns a list of strings which trigger a completion menu for this language.
2076    /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2077    pub fn completion_triggers(&self) -> &[String] {
2078        &self.completion_triggers
2079    }
2080}
2081
2082#[doc(hidden)]
2083#[cfg(any(test, feature = "test-support"))]
2084impl Buffer {
2085    pub fn edit_via_marked_text(
2086        &mut self,
2087        marked_string: &str,
2088        autoindent_mode: Option<AutoindentMode>,
2089        cx: &mut ModelContext<Self>,
2090    ) {
2091        let edits = self.edits_for_marked_text(marked_string);
2092        self.edit(edits, autoindent_mode, cx);
2093    }
2094
2095    pub fn set_group_interval(&mut self, group_interval: Duration) {
2096        self.text.set_group_interval(group_interval);
2097    }
2098
2099    pub fn randomly_edit<T>(
2100        &mut self,
2101        rng: &mut T,
2102        old_range_count: usize,
2103        cx: &mut ModelContext<Self>,
2104    ) where
2105        T: rand::Rng,
2106    {
2107        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2108        let mut last_end = None;
2109        for _ in 0..old_range_count {
2110            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2111                break;
2112            }
2113
2114            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2115            let mut range = self.random_byte_range(new_start, rng);
2116            if rng.gen_bool(0.2) {
2117                mem::swap(&mut range.start, &mut range.end);
2118            }
2119            last_end = Some(range.end);
2120
2121            let new_text_len = rng.gen_range(0..10);
2122            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2123
2124            edits.push((range, new_text));
2125        }
2126        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2127        self.edit(edits, None, cx);
2128    }
2129
2130    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
2131        let was_dirty = self.is_dirty();
2132        let old_version = self.version.clone();
2133
2134        let ops = self.text.randomly_undo_redo(rng);
2135        if !ops.is_empty() {
2136            for op in ops {
2137                self.send_operation(Operation::Buffer(op), cx);
2138                self.did_edit(&old_version, was_dirty, cx);
2139            }
2140        }
2141    }
2142}
2143
2144impl EventEmitter<Event> for Buffer {}
2145
2146impl Deref for Buffer {
2147    type Target = TextBuffer;
2148
2149    fn deref(&self) -> &Self::Target {
2150        &self.text
2151    }
2152}
2153
2154impl BufferSnapshot {
2155    /// Returns [`IndentSize`] for a given line that respects user settings and /// language preferences.
2156    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2157        indent_size_for_line(self, row)
2158    }
2159    /// Returns [`IndentSize`] for a given position that respects user settings
2160    /// and language preferences.
2161    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &AppContext) -> IndentSize {
2162        let settings = language_settings(self.language_at(position), self.file(), cx);
2163        if settings.hard_tabs {
2164            IndentSize::tab()
2165        } else {
2166            IndentSize::spaces(settings.tab_size.get())
2167        }
2168    }
2169
2170    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2171    /// is passed in as `single_indent_size`.
2172    pub fn suggested_indents(
2173        &self,
2174        rows: impl Iterator<Item = u32>,
2175        single_indent_size: IndentSize,
2176    ) -> BTreeMap<u32, IndentSize> {
2177        let mut result = BTreeMap::new();
2178
2179        for row_range in contiguous_ranges(rows, 10) {
2180            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2181                Some(suggestions) => suggestions,
2182                _ => break,
2183            };
2184
2185            for (row, suggestion) in row_range.zip(suggestions) {
2186                let indent_size = if let Some(suggestion) = suggestion {
2187                    result
2188                        .get(&suggestion.basis_row)
2189                        .copied()
2190                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2191                        .with_delta(suggestion.delta, single_indent_size)
2192                } else {
2193                    self.indent_size_for_line(row)
2194                };
2195
2196                result.insert(row, indent_size);
2197            }
2198        }
2199
2200        result
2201    }
2202
2203    fn suggest_autoindents(
2204        &self,
2205        row_range: Range<u32>,
2206    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2207        let config = &self.language.as_ref()?.config;
2208        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2209
2210        // Find the suggested indentation ranges based on the syntax tree.
2211        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2212        let end = Point::new(row_range.end, 0);
2213        let range = (start..end).to_offset(&self.text);
2214        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2215            Some(&grammar.indents_config.as_ref()?.query)
2216        });
2217        let indent_configs = matches
2218            .grammars()
2219            .iter()
2220            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2221            .collect::<Vec<_>>();
2222
2223        let mut indent_ranges = Vec::<Range<Point>>::new();
2224        let mut outdent_positions = Vec::<Point>::new();
2225        while let Some(mat) = matches.peek() {
2226            let mut start: Option<Point> = None;
2227            let mut end: Option<Point> = None;
2228
2229            let config = &indent_configs[mat.grammar_index];
2230            for capture in mat.captures {
2231                if capture.index == config.indent_capture_ix {
2232                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2233                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2234                } else if Some(capture.index) == config.start_capture_ix {
2235                    start = Some(Point::from_ts_point(capture.node.end_position()));
2236                } else if Some(capture.index) == config.end_capture_ix {
2237                    end = Some(Point::from_ts_point(capture.node.start_position()));
2238                } else if Some(capture.index) == config.outdent_capture_ix {
2239                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2240                }
2241            }
2242
2243            matches.advance();
2244            if let Some((start, end)) = start.zip(end) {
2245                if start.row == end.row {
2246                    continue;
2247                }
2248
2249                let range = start..end;
2250                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2251                    Err(ix) => indent_ranges.insert(ix, range),
2252                    Ok(ix) => {
2253                        let prev_range = &mut indent_ranges[ix];
2254                        prev_range.end = prev_range.end.max(range.end);
2255                    }
2256                }
2257            }
2258        }
2259
2260        let mut error_ranges = Vec::<Range<Point>>::new();
2261        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2262            Some(&grammar.error_query)
2263        });
2264        while let Some(mat) = matches.peek() {
2265            let node = mat.captures[0].node;
2266            let start = Point::from_ts_point(node.start_position());
2267            let end = Point::from_ts_point(node.end_position());
2268            let range = start..end;
2269            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2270                Ok(ix) | Err(ix) => ix,
2271            };
2272            let mut end_ix = ix;
2273            while let Some(existing_range) = error_ranges.get(end_ix) {
2274                if existing_range.end < end {
2275                    end_ix += 1;
2276                } else {
2277                    break;
2278                }
2279            }
2280            error_ranges.splice(ix..end_ix, [range]);
2281            matches.advance();
2282        }
2283
2284        outdent_positions.sort();
2285        for outdent_position in outdent_positions {
2286            // find the innermost indent range containing this outdent_position
2287            // set its end to the outdent position
2288            if let Some(range_to_truncate) = indent_ranges
2289                .iter_mut()
2290                .filter(|indent_range| indent_range.contains(&outdent_position))
2291                .last()
2292            {
2293                range_to_truncate.end = outdent_position;
2294            }
2295        }
2296
2297        // Find the suggested indentation increases and decreased based on regexes.
2298        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2299        self.for_each_line(
2300            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2301                ..Point::new(row_range.end, 0),
2302            |row, line| {
2303                if config
2304                    .decrease_indent_pattern
2305                    .as_ref()
2306                    .map_or(false, |regex| regex.is_match(line))
2307                {
2308                    indent_change_rows.push((row, Ordering::Less));
2309                }
2310                if config
2311                    .increase_indent_pattern
2312                    .as_ref()
2313                    .map_or(false, |regex| regex.is_match(line))
2314                {
2315                    indent_change_rows.push((row + 1, Ordering::Greater));
2316                }
2317            },
2318        );
2319
2320        let mut indent_changes = indent_change_rows.into_iter().peekable();
2321        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2322            prev_non_blank_row.unwrap_or(0)
2323        } else {
2324            row_range.start.saturating_sub(1)
2325        };
2326        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2327        Some(row_range.map(move |row| {
2328            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2329
2330            let mut indent_from_prev_row = false;
2331            let mut outdent_from_prev_row = false;
2332            let mut outdent_to_row = u32::MAX;
2333
2334            while let Some((indent_row, delta)) = indent_changes.peek() {
2335                match indent_row.cmp(&row) {
2336                    Ordering::Equal => match delta {
2337                        Ordering::Less => outdent_from_prev_row = true,
2338                        Ordering::Greater => indent_from_prev_row = true,
2339                        _ => {}
2340                    },
2341
2342                    Ordering::Greater => break,
2343                    Ordering::Less => {}
2344                }
2345
2346                indent_changes.next();
2347            }
2348
2349            for range in &indent_ranges {
2350                if range.start.row >= row {
2351                    break;
2352                }
2353                if range.start.row == prev_row && range.end > row_start {
2354                    indent_from_prev_row = true;
2355                }
2356                if range.end > prev_row_start && range.end <= row_start {
2357                    outdent_to_row = outdent_to_row.min(range.start.row);
2358                }
2359            }
2360
2361            let within_error = error_ranges
2362                .iter()
2363                .any(|e| e.start.row < row && e.end > row_start);
2364
2365            let suggestion = if outdent_to_row == prev_row
2366                || (outdent_from_prev_row && indent_from_prev_row)
2367            {
2368                Some(IndentSuggestion {
2369                    basis_row: prev_row,
2370                    delta: Ordering::Equal,
2371                    within_error,
2372                })
2373            } else if indent_from_prev_row {
2374                Some(IndentSuggestion {
2375                    basis_row: prev_row,
2376                    delta: Ordering::Greater,
2377                    within_error,
2378                })
2379            } else if outdent_to_row < prev_row {
2380                Some(IndentSuggestion {
2381                    basis_row: outdent_to_row,
2382                    delta: Ordering::Equal,
2383                    within_error,
2384                })
2385            } else if outdent_from_prev_row {
2386                Some(IndentSuggestion {
2387                    basis_row: prev_row,
2388                    delta: Ordering::Less,
2389                    within_error,
2390                })
2391            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
2392            {
2393                Some(IndentSuggestion {
2394                    basis_row: prev_row,
2395                    delta: Ordering::Equal,
2396                    within_error,
2397                })
2398            } else {
2399                None
2400            };
2401
2402            prev_row = row;
2403            prev_row_start = row_start;
2404            suggestion
2405        }))
2406    }
2407
2408    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2409        while row > 0 {
2410            row -= 1;
2411            if !self.is_line_blank(row) {
2412                return Some(row);
2413            }
2414        }
2415        None
2416    }
2417
2418    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
2419    /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
2420    /// returned in chunks where each chunk has a single syntax highlighting style and
2421    /// diagnostic status.
2422    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
2423        let range = range.start.to_offset(self)..range.end.to_offset(self);
2424
2425        let mut syntax = None;
2426        let mut diagnostic_endpoints = Vec::new();
2427        if language_aware {
2428            let captures = self.syntax.captures(range.clone(), &self.text, |grammar| {
2429                grammar.highlights_query.as_ref()
2430            });
2431            let highlight_maps = captures
2432                .grammars()
2433                .into_iter()
2434                .map(|grammar| grammar.highlight_map())
2435                .collect();
2436            syntax = Some((captures, highlight_maps));
2437            for entry in self.diagnostics_in_range::<_, usize>(range.clone(), false) {
2438                diagnostic_endpoints.push(DiagnosticEndpoint {
2439                    offset: entry.range.start,
2440                    is_start: true,
2441                    severity: entry.diagnostic.severity,
2442                    is_unnecessary: entry.diagnostic.is_unnecessary,
2443                });
2444                diagnostic_endpoints.push(DiagnosticEndpoint {
2445                    offset: entry.range.end,
2446                    is_start: false,
2447                    severity: entry.diagnostic.severity,
2448                    is_unnecessary: entry.diagnostic.is_unnecessary,
2449                });
2450            }
2451            diagnostic_endpoints
2452                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
2453        }
2454
2455        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostic_endpoints)
2456    }
2457
2458    /// Invokes the given callback for each line of text in the given range of the buffer.
2459    /// Uses callback to avoid allocating a string for each line.
2460    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
2461        let mut line = String::new();
2462        let mut row = range.start.row;
2463        for chunk in self
2464            .as_rope()
2465            .chunks_in_range(range.to_offset(self))
2466            .chain(["\n"])
2467        {
2468            for (newline_ix, text) in chunk.split('\n').enumerate() {
2469                if newline_ix > 0 {
2470                    callback(row, &line);
2471                    row += 1;
2472                    line.clear();
2473                }
2474                line.push_str(text);
2475            }
2476        }
2477    }
2478
2479    /// Iterates over every [`SyntaxLayer`] in the buffer.
2480    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
2481        self.syntax.layers_for_range(0..self.len(), &self.text)
2482    }
2483
2484    fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
2485        let offset = position.to_offset(self);
2486        self.syntax
2487            .layers_for_range(offset..offset, &self.text)
2488            .filter(|l| l.node().end_byte() > offset)
2489            .last()
2490    }
2491
2492    /// Returns the [Language] at the given location.
2493    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
2494        self.syntax_layer_at(position)
2495            .map(|info| info.language)
2496            .or(self.language.as_ref())
2497    }
2498
2499    /// Returns the settings for the language at the given location.
2500    pub fn settings_at<'a, D: ToOffset>(
2501        &self,
2502        position: D,
2503        cx: &'a AppContext,
2504    ) -> &'a LanguageSettings {
2505        language_settings(self.language_at(position), self.file.as_ref(), cx)
2506    }
2507
2508    /// Returns the [LanguageScope] at the given location.
2509    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
2510        let offset = position.to_offset(self);
2511        let mut scope = None;
2512        let mut smallest_range: Option<Range<usize>> = None;
2513
2514        // Use the layer that has the smallest node intersecting the given point.
2515        for layer in self.syntax.layers_for_range(offset..offset, &self.text) {
2516            let mut cursor = layer.node().walk();
2517
2518            let mut range = None;
2519            loop {
2520                let child_range = cursor.node().byte_range();
2521                if !child_range.to_inclusive().contains(&offset) {
2522                    break;
2523                }
2524
2525                range = Some(child_range);
2526                if cursor.goto_first_child_for_byte(offset).is_none() {
2527                    break;
2528                }
2529            }
2530
2531            if let Some(range) = range {
2532                if smallest_range
2533                    .as_ref()
2534                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
2535                {
2536                    smallest_range = Some(range);
2537                    scope = Some(LanguageScope {
2538                        language: layer.language.clone(),
2539                        override_id: layer.override_id(offset, &self.text),
2540                    });
2541                }
2542            }
2543        }
2544
2545        scope.or_else(|| {
2546            self.language.clone().map(|language| LanguageScope {
2547                language,
2548                override_id: None,
2549            })
2550        })
2551    }
2552
2553    /// Returns a tuple of the range and character kind of the word
2554    /// surrounding the given position.
2555    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2556        let mut start = start.to_offset(self);
2557        let mut end = start;
2558        let mut next_chars = self.chars_at(start).peekable();
2559        let mut prev_chars = self.reversed_chars_at(start).peekable();
2560
2561        let scope = self.language_scope_at(start);
2562        let kind = |c| char_kind(&scope, c);
2563        let word_kind = cmp::max(
2564            prev_chars.peek().copied().map(kind),
2565            next_chars.peek().copied().map(kind),
2566        );
2567
2568        for ch in prev_chars {
2569            if Some(kind(ch)) == word_kind && ch != '\n' {
2570                start -= ch.len_utf8();
2571            } else {
2572                break;
2573            }
2574        }
2575
2576        for ch in next_chars {
2577            if Some(kind(ch)) == word_kind && ch != '\n' {
2578                end += ch.len_utf8();
2579            } else {
2580                break;
2581            }
2582        }
2583
2584        (start..end, word_kind)
2585    }
2586
2587    /// Returns the range for the closes syntax node enclosing the given range.
2588    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2589        let range = range.start.to_offset(self)..range.end.to_offset(self);
2590        let mut result: Option<Range<usize>> = None;
2591        'outer: for layer in self.syntax.layers_for_range(range.clone(), &self.text) {
2592            let mut cursor = layer.node().walk();
2593
2594            // Descend to the first leaf that touches the start of the range,
2595            // and if the range is non-empty, extends beyond the start.
2596            while cursor.goto_first_child_for_byte(range.start).is_some() {
2597                if !range.is_empty() && cursor.node().end_byte() == range.start {
2598                    cursor.goto_next_sibling();
2599                }
2600            }
2601
2602            // Ascend to the smallest ancestor that strictly contains the range.
2603            loop {
2604                let node_range = cursor.node().byte_range();
2605                if node_range.start <= range.start
2606                    && node_range.end >= range.end
2607                    && node_range.len() > range.len()
2608                {
2609                    break;
2610                }
2611                if !cursor.goto_parent() {
2612                    continue 'outer;
2613                }
2614            }
2615
2616            let left_node = cursor.node();
2617            let mut layer_result = left_node.byte_range();
2618
2619            // For an empty range, try to find another node immediately to the right of the range.
2620            if left_node.end_byte() == range.start {
2621                let mut right_node = None;
2622                while !cursor.goto_next_sibling() {
2623                    if !cursor.goto_parent() {
2624                        break;
2625                    }
2626                }
2627
2628                while cursor.node().start_byte() == range.start {
2629                    right_node = Some(cursor.node());
2630                    if !cursor.goto_first_child() {
2631                        break;
2632                    }
2633                }
2634
2635                // If there is a candidate node on both sides of the (empty) range, then
2636                // decide between the two by favoring a named node over an anonymous token.
2637                // If both nodes are the same in that regard, favor the right one.
2638                if let Some(right_node) = right_node {
2639                    if right_node.is_named() || !left_node.is_named() {
2640                        layer_result = right_node.byte_range();
2641                    }
2642                }
2643            }
2644
2645            if let Some(previous_result) = &result {
2646                if previous_result.len() < layer_result.len() {
2647                    continue;
2648                }
2649            }
2650            result = Some(layer_result);
2651        }
2652
2653        result
2654    }
2655
2656    /// Returns the outline for the buffer.
2657    ///
2658    /// This method allows passing an optional [SyntaxTheme] to
2659    /// syntax-highlight the returned symbols.
2660    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2661        self.outline_items_containing(0..self.len(), true, theme)
2662            .map(Outline::new)
2663    }
2664
2665    /// Returns all the symbols that contain the given position.
2666    ///
2667    /// This method allows passing an optional [SyntaxTheme] to
2668    /// syntax-highlight the returned symbols.
2669    pub fn symbols_containing<T: ToOffset>(
2670        &self,
2671        position: T,
2672        theme: Option<&SyntaxTheme>,
2673    ) -> Option<Vec<OutlineItem<Anchor>>> {
2674        let position = position.to_offset(self);
2675        let mut items = self.outline_items_containing(
2676            position.saturating_sub(1)..self.len().min(position + 1),
2677            false,
2678            theme,
2679        )?;
2680        let mut prev_depth = None;
2681        items.retain(|item| {
2682            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
2683            prev_depth = Some(item.depth);
2684            result
2685        });
2686        Some(items)
2687    }
2688
2689    fn outline_items_containing(
2690        &self,
2691        range: Range<usize>,
2692        include_extra_context: bool,
2693        theme: Option<&SyntaxTheme>,
2694    ) -> Option<Vec<OutlineItem<Anchor>>> {
2695        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2696            grammar.outline_config.as_ref().map(|c| &c.query)
2697        });
2698        let configs = matches
2699            .grammars()
2700            .iter()
2701            .map(|g| g.outline_config.as_ref().unwrap())
2702            .collect::<Vec<_>>();
2703
2704        let mut stack = Vec::<Range<usize>>::new();
2705        let mut items = Vec::new();
2706        while let Some(mat) = matches.peek() {
2707            let config = &configs[mat.grammar_index];
2708            let item_node = mat.captures.iter().find_map(|cap| {
2709                if cap.index == config.item_capture_ix {
2710                    Some(cap.node)
2711                } else {
2712                    None
2713                }
2714            })?;
2715
2716            let item_range = item_node.byte_range();
2717            if item_range.end < range.start || item_range.start > range.end {
2718                matches.advance();
2719                continue;
2720            }
2721
2722            let mut buffer_ranges = Vec::new();
2723            for capture in mat.captures {
2724                let node_is_name;
2725                if capture.index == config.name_capture_ix {
2726                    node_is_name = true;
2727                } else if Some(capture.index) == config.context_capture_ix
2728                    || (Some(capture.index) == config.extra_context_capture_ix
2729                        && include_extra_context)
2730                {
2731                    node_is_name = false;
2732                } else {
2733                    continue;
2734                }
2735
2736                let mut range = capture.node.start_byte()..capture.node.end_byte();
2737                let start = capture.node.start_position();
2738                if capture.node.end_position().row > start.row {
2739                    range.end =
2740                        range.start + self.line_len(start.row as u32) as usize - start.column;
2741                }
2742
2743                buffer_ranges.push((range, node_is_name));
2744            }
2745
2746            if buffer_ranges.is_empty() {
2747                continue;
2748            }
2749
2750            let mut text = String::new();
2751            let mut highlight_ranges = Vec::new();
2752            let mut name_ranges = Vec::new();
2753            let mut chunks = self.chunks(
2754                buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
2755                true,
2756            );
2757            let mut last_buffer_range_end = 0;
2758            for (buffer_range, is_name) in buffer_ranges {
2759                if !text.is_empty() && buffer_range.start > last_buffer_range_end {
2760                    text.push(' ');
2761                }
2762                last_buffer_range_end = buffer_range.end;
2763                if is_name {
2764                    let mut start = text.len();
2765                    let end = start + buffer_range.len();
2766
2767                    // When multiple names are captured, then the matcheable text
2768                    // includes the whitespace in between the names.
2769                    if !name_ranges.is_empty() {
2770                        start -= 1;
2771                    }
2772
2773                    name_ranges.push(start..end);
2774                }
2775
2776                let mut offset = buffer_range.start;
2777                chunks.seek(offset);
2778                for mut chunk in chunks.by_ref() {
2779                    if chunk.text.len() > buffer_range.end - offset {
2780                        chunk.text = &chunk.text[0..(buffer_range.end - offset)];
2781                        offset = buffer_range.end;
2782                    } else {
2783                        offset += chunk.text.len();
2784                    }
2785                    let style = chunk
2786                        .syntax_highlight_id
2787                        .zip(theme)
2788                        .and_then(|(highlight, theme)| highlight.style(theme));
2789                    if let Some(style) = style {
2790                        let start = text.len();
2791                        let end = start + chunk.text.len();
2792                        highlight_ranges.push((start..end, style));
2793                    }
2794                    text.push_str(chunk.text);
2795                    if offset >= buffer_range.end {
2796                        break;
2797                    }
2798                }
2799            }
2800
2801            matches.advance();
2802            while stack.last().map_or(false, |prev_range| {
2803                prev_range.start > item_range.start || prev_range.end < item_range.end
2804            }) {
2805                stack.pop();
2806            }
2807            stack.push(item_range.clone());
2808
2809            items.push(OutlineItem {
2810                depth: stack.len() - 1,
2811                range: self.anchor_after(item_range.start)..self.anchor_before(item_range.end),
2812                text,
2813                highlight_ranges,
2814                name_ranges,
2815            })
2816        }
2817        Some(items)
2818    }
2819
2820    /// For each grammar in the language, runs the provided
2821    /// [tree_sitter::Query] against the given range.
2822    pub fn matches(
2823        &self,
2824        range: Range<usize>,
2825        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
2826    ) -> SyntaxMapMatches {
2827        self.syntax.matches(range, self, query)
2828    }
2829
2830    /// Returns bracket range pairs overlapping or adjacent to `range`
2831    pub fn bracket_ranges<'a, T: ToOffset>(
2832        &'a self,
2833        range: Range<T>,
2834    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a {
2835        // Find bracket pairs that *inclusively* contain the given range.
2836        let range = range.start.to_offset(self).saturating_sub(1)
2837            ..self.len().min(range.end.to_offset(self) + 1);
2838
2839        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2840            grammar.brackets_config.as_ref().map(|c| &c.query)
2841        });
2842        let configs = matches
2843            .grammars()
2844            .iter()
2845            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
2846            .collect::<Vec<_>>();
2847
2848        iter::from_fn(move || {
2849            while let Some(mat) = matches.peek() {
2850                let mut open = None;
2851                let mut close = None;
2852                let config = &configs[mat.grammar_index];
2853                for capture in mat.captures {
2854                    if capture.index == config.open_capture_ix {
2855                        open = Some(capture.node.byte_range());
2856                    } else if capture.index == config.close_capture_ix {
2857                        close = Some(capture.node.byte_range());
2858                    }
2859                }
2860
2861                matches.advance();
2862
2863                let Some((open, close)) = open.zip(close) else {
2864                    continue;
2865                };
2866
2867                let bracket_range = open.start..=close.end;
2868                if !bracket_range.overlaps(&range) {
2869                    continue;
2870                }
2871
2872                return Some((open, close));
2873            }
2874            None
2875        })
2876    }
2877
2878    /// Returns selections for remote peers intersecting the given range.
2879    #[allow(clippy::type_complexity)]
2880    pub fn remote_selections_in_range(
2881        &self,
2882        range: Range<Anchor>,
2883    ) -> impl Iterator<
2884        Item = (
2885            ReplicaId,
2886            bool,
2887            CursorShape,
2888            impl Iterator<Item = &Selection<Anchor>> + '_,
2889        ),
2890    > + '_ {
2891        self.remote_selections
2892            .iter()
2893            .filter(|(replica_id, set)| {
2894                **replica_id != self.text.replica_id() && !set.selections.is_empty()
2895            })
2896            .map(move |(replica_id, set)| {
2897                let start_ix = match set.selections.binary_search_by(|probe| {
2898                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
2899                }) {
2900                    Ok(ix) | Err(ix) => ix,
2901                };
2902                let end_ix = match set.selections.binary_search_by(|probe| {
2903                    probe.start.cmp(&range.end, self).then(Ordering::Less)
2904                }) {
2905                    Ok(ix) | Err(ix) => ix,
2906                };
2907
2908                (
2909                    *replica_id,
2910                    set.line_mode,
2911                    set.cursor_shape,
2912                    set.selections[start_ix..end_ix].iter(),
2913                )
2914            })
2915    }
2916
2917    /// Whether the buffer contains any git changes.
2918    pub fn has_git_diff(&self) -> bool {
2919        !self.git_diff.is_empty()
2920    }
2921
2922    /// Returns all the Git diff hunks intersecting the given
2923    /// row range.
2924    pub fn git_diff_hunks_in_row_range<'a>(
2925        &'a self,
2926        range: Range<u32>,
2927    ) -> impl 'a + Iterator<Item = git::diff::DiffHunk<u32>> {
2928        self.git_diff.hunks_in_row_range(range, self)
2929    }
2930
2931    /// Returns all the Git diff hunks intersecting the given
2932    /// range.
2933    pub fn git_diff_hunks_intersecting_range<'a>(
2934        &'a self,
2935        range: Range<Anchor>,
2936    ) -> impl 'a + Iterator<Item = git::diff::DiffHunk<u32>> {
2937        self.git_diff.hunks_intersecting_range(range, self)
2938    }
2939
2940    /// Returns all the Git diff hunks intersecting the given
2941    /// range, in reverse order.
2942    pub fn git_diff_hunks_intersecting_range_rev<'a>(
2943        &'a self,
2944        range: Range<Anchor>,
2945    ) -> impl 'a + Iterator<Item = git::diff::DiffHunk<u32>> {
2946        self.git_diff.hunks_intersecting_range_rev(range, self)
2947    }
2948
2949    /// Returns all the diagnostics intersecting the given range.
2950    pub fn diagnostics_in_range<'a, T, O>(
2951        &'a self,
2952        search_range: Range<T>,
2953        reversed: bool,
2954    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2955    where
2956        T: 'a + Clone + ToOffset,
2957        O: 'a + FromAnchor + Ord,
2958    {
2959        let mut iterators: Vec<_> = self
2960            .diagnostics
2961            .iter()
2962            .map(|(_, collection)| {
2963                collection
2964                    .range::<T, O>(search_range.clone(), self, true, reversed)
2965                    .peekable()
2966            })
2967            .collect();
2968
2969        std::iter::from_fn(move || {
2970            let (next_ix, _) = iterators
2971                .iter_mut()
2972                .enumerate()
2973                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
2974                .min_by(|(_, a), (_, b)| a.range.start.cmp(&b.range.start))?;
2975            iterators[next_ix].next()
2976        })
2977    }
2978
2979    /// Returns all the diagnostic groups associated with the given
2980    /// language server id. If no language server id is provided,
2981    /// all diagnostics groups are returned.
2982    pub fn diagnostic_groups(
2983        &self,
2984        language_server_id: Option<LanguageServerId>,
2985    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
2986        let mut groups = Vec::new();
2987
2988        if let Some(language_server_id) = language_server_id {
2989            if let Ok(ix) = self
2990                .diagnostics
2991                .binary_search_by_key(&language_server_id, |e| e.0)
2992            {
2993                self.diagnostics[ix]
2994                    .1
2995                    .groups(language_server_id, &mut groups, self);
2996            }
2997        } else {
2998            for (language_server_id, diagnostics) in self.diagnostics.iter() {
2999                diagnostics.groups(*language_server_id, &mut groups, self);
3000            }
3001        }
3002
3003        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
3004            let a_start = &group_a.entries[group_a.primary_ix].range.start;
3005            let b_start = &group_b.entries[group_b.primary_ix].range.start;
3006            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
3007        });
3008
3009        groups
3010    }
3011
3012    /// Returns an iterator over the diagnostics for the given group.
3013    pub fn diagnostic_group<'a, O>(
3014        &'a self,
3015        group_id: usize,
3016    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3017    where
3018        O: 'a + FromAnchor,
3019    {
3020        self.diagnostics
3021            .iter()
3022            .flat_map(move |(_, set)| set.group(group_id, self))
3023    }
3024
3025    /// The number of times diagnostics were updated.
3026    pub fn diagnostics_update_count(&self) -> usize {
3027        self.diagnostics_update_count
3028    }
3029
3030    /// The number of times the buffer was parsed.
3031    pub fn parse_count(&self) -> usize {
3032        self.parse_count
3033    }
3034
3035    /// The number of times selections were updated.
3036    pub fn selections_update_count(&self) -> usize {
3037        self.selections_update_count
3038    }
3039
3040    /// Returns a snapshot of underlying file.
3041    pub fn file(&self) -> Option<&Arc<dyn File>> {
3042        self.file.as_ref()
3043    }
3044
3045    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
3046    pub fn resolve_file_path(&self, cx: &AppContext, include_root: bool) -> Option<PathBuf> {
3047        if let Some(file) = self.file() {
3048            if file.path().file_name().is_none() || include_root {
3049                Some(file.full_path(cx))
3050            } else {
3051                Some(file.path().to_path_buf())
3052            }
3053        } else {
3054            None
3055        }
3056    }
3057
3058    /// The number of times the underlying file was updated.
3059    pub fn file_update_count(&self) -> usize {
3060        self.file_update_count
3061    }
3062
3063    /// The number of times the git diff status was updated.
3064    pub fn git_diff_update_count(&self) -> usize {
3065        self.git_diff_update_count
3066    }
3067}
3068
3069fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
3070    indent_size_for_text(text.chars_at(Point::new(row, 0)))
3071}
3072
3073fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
3074    let mut result = IndentSize::spaces(0);
3075    for c in text {
3076        let kind = match c {
3077            ' ' => IndentKind::Space,
3078            '\t' => IndentKind::Tab,
3079            _ => break,
3080        };
3081        if result.len == 0 {
3082            result.kind = kind;
3083        }
3084        result.len += 1;
3085    }
3086    result
3087}
3088
3089impl Clone for BufferSnapshot {
3090    fn clone(&self) -> Self {
3091        Self {
3092            text: self.text.clone(),
3093            git_diff: self.git_diff.clone(),
3094            syntax: self.syntax.clone(),
3095            file: self.file.clone(),
3096            remote_selections: self.remote_selections.clone(),
3097            diagnostics: self.diagnostics.clone(),
3098            selections_update_count: self.selections_update_count,
3099            diagnostics_update_count: self.diagnostics_update_count,
3100            file_update_count: self.file_update_count,
3101            git_diff_update_count: self.git_diff_update_count,
3102            language: self.language.clone(),
3103            parse_count: self.parse_count,
3104        }
3105    }
3106}
3107
3108impl Deref for BufferSnapshot {
3109    type Target = text::BufferSnapshot;
3110
3111    fn deref(&self) -> &Self::Target {
3112        &self.text
3113    }
3114}
3115
3116unsafe impl<'a> Send for BufferChunks<'a> {}
3117
3118impl<'a> BufferChunks<'a> {
3119    pub(crate) fn new(
3120        text: &'a Rope,
3121        range: Range<usize>,
3122        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
3123        diagnostic_endpoints: Vec<DiagnosticEndpoint>,
3124    ) -> Self {
3125        let mut highlights = None;
3126        if let Some((captures, highlight_maps)) = syntax {
3127            highlights = Some(BufferChunkHighlights {
3128                captures,
3129                next_capture: None,
3130                stack: Default::default(),
3131                highlight_maps,
3132            })
3133        }
3134
3135        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
3136        let chunks = text.chunks_in_range(range.clone());
3137
3138        BufferChunks {
3139            range,
3140            chunks,
3141            diagnostic_endpoints,
3142            error_depth: 0,
3143            warning_depth: 0,
3144            information_depth: 0,
3145            hint_depth: 0,
3146            unnecessary_depth: 0,
3147            highlights,
3148        }
3149    }
3150
3151    /// Seeks to the given byte offset in the buffer.
3152    pub fn seek(&mut self, offset: usize) {
3153        self.range.start = offset;
3154        self.chunks.seek(self.range.start);
3155        if let Some(highlights) = self.highlights.as_mut() {
3156            highlights
3157                .stack
3158                .retain(|(end_offset, _)| *end_offset > offset);
3159            if let Some(capture) = &highlights.next_capture {
3160                if offset >= capture.node.start_byte() {
3161                    let next_capture_end = capture.node.end_byte();
3162                    if offset < next_capture_end {
3163                        highlights.stack.push((
3164                            next_capture_end,
3165                            highlights.highlight_maps[capture.grammar_index].get(capture.index),
3166                        ));
3167                    }
3168                    highlights.next_capture.take();
3169                }
3170            }
3171            highlights.captures.set_byte_range(self.range.clone());
3172        }
3173    }
3174
3175    /// The current byte offset in the buffer.
3176    pub fn offset(&self) -> usize {
3177        self.range.start
3178    }
3179
3180    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
3181        let depth = match endpoint.severity {
3182            DiagnosticSeverity::ERROR => &mut self.error_depth,
3183            DiagnosticSeverity::WARNING => &mut self.warning_depth,
3184            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
3185            DiagnosticSeverity::HINT => &mut self.hint_depth,
3186            _ => return,
3187        };
3188        if endpoint.is_start {
3189            *depth += 1;
3190        } else {
3191            *depth -= 1;
3192        }
3193
3194        if endpoint.is_unnecessary {
3195            if endpoint.is_start {
3196                self.unnecessary_depth += 1;
3197            } else {
3198                self.unnecessary_depth -= 1;
3199            }
3200        }
3201    }
3202
3203    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
3204        if self.error_depth > 0 {
3205            Some(DiagnosticSeverity::ERROR)
3206        } else if self.warning_depth > 0 {
3207            Some(DiagnosticSeverity::WARNING)
3208        } else if self.information_depth > 0 {
3209            Some(DiagnosticSeverity::INFORMATION)
3210        } else if self.hint_depth > 0 {
3211            Some(DiagnosticSeverity::HINT)
3212        } else {
3213            None
3214        }
3215    }
3216
3217    fn current_code_is_unnecessary(&self) -> bool {
3218        self.unnecessary_depth > 0
3219    }
3220}
3221
3222impl<'a> Iterator for BufferChunks<'a> {
3223    type Item = Chunk<'a>;
3224
3225    fn next(&mut self) -> Option<Self::Item> {
3226        let mut next_capture_start = usize::MAX;
3227        let mut next_diagnostic_endpoint = usize::MAX;
3228
3229        if let Some(highlights) = self.highlights.as_mut() {
3230            while let Some((parent_capture_end, _)) = highlights.stack.last() {
3231                if *parent_capture_end <= self.range.start {
3232                    highlights.stack.pop();
3233                } else {
3234                    break;
3235                }
3236            }
3237
3238            if highlights.next_capture.is_none() {
3239                highlights.next_capture = highlights.captures.next();
3240            }
3241
3242            while let Some(capture) = highlights.next_capture.as_ref() {
3243                if self.range.start < capture.node.start_byte() {
3244                    next_capture_start = capture.node.start_byte();
3245                    break;
3246                } else {
3247                    let highlight_id =
3248                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
3249                    highlights
3250                        .stack
3251                        .push((capture.node.end_byte(), highlight_id));
3252                    highlights.next_capture = highlights.captures.next();
3253                }
3254            }
3255        }
3256
3257        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
3258            if endpoint.offset <= self.range.start {
3259                self.update_diagnostic_depths(endpoint);
3260                self.diagnostic_endpoints.next();
3261            } else {
3262                next_diagnostic_endpoint = endpoint.offset;
3263                break;
3264            }
3265        }
3266
3267        if let Some(chunk) = self.chunks.peek() {
3268            let chunk_start = self.range.start;
3269            let mut chunk_end = (self.chunks.offset() + chunk.len())
3270                .min(next_capture_start)
3271                .min(next_diagnostic_endpoint);
3272            let mut highlight_id = None;
3273            if let Some(highlights) = self.highlights.as_ref() {
3274                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
3275                    chunk_end = chunk_end.min(*parent_capture_end);
3276                    highlight_id = Some(*parent_highlight_id);
3277                }
3278            }
3279
3280            let slice =
3281                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
3282            self.range.start = chunk_end;
3283            if self.range.start == self.chunks.offset() + chunk.len() {
3284                self.chunks.next().unwrap();
3285            }
3286
3287            Some(Chunk {
3288                text: slice,
3289                syntax_highlight_id: highlight_id,
3290                diagnostic_severity: self.current_diagnostic_severity(),
3291                is_unnecessary: self.current_code_is_unnecessary(),
3292                ..Default::default()
3293            })
3294        } else {
3295            None
3296        }
3297    }
3298}
3299
3300impl operation_queue::Operation for Operation {
3301    fn lamport_timestamp(&self) -> clock::Lamport {
3302        match self {
3303            Operation::Buffer(_) => {
3304                unreachable!("buffer operations should never be deferred at this layer")
3305            }
3306            Operation::UpdateDiagnostics {
3307                lamport_timestamp, ..
3308            }
3309            | Operation::UpdateSelections {
3310                lamport_timestamp, ..
3311            }
3312            | Operation::UpdateCompletionTriggers {
3313                lamport_timestamp, ..
3314            } => *lamport_timestamp,
3315        }
3316    }
3317}
3318
3319impl Default for Diagnostic {
3320    fn default() -> Self {
3321        Self {
3322            source: Default::default(),
3323            code: None,
3324            severity: DiagnosticSeverity::ERROR,
3325            message: Default::default(),
3326            group_id: 0,
3327            is_primary: false,
3328            is_disk_based: false,
3329            is_unnecessary: false,
3330        }
3331    }
3332}
3333
3334impl IndentSize {
3335    /// Returns an [IndentSize] representing the given spaces.
3336    pub fn spaces(len: u32) -> Self {
3337        Self {
3338            len,
3339            kind: IndentKind::Space,
3340        }
3341    }
3342
3343    /// Returns an [IndentSize] representing a tab.
3344    pub fn tab() -> Self {
3345        Self {
3346            len: 1,
3347            kind: IndentKind::Tab,
3348        }
3349    }
3350
3351    /// An iterator over the characters represented by this [IndentSize].
3352    pub fn chars(&self) -> impl Iterator<Item = char> {
3353        iter::repeat(self.char()).take(self.len as usize)
3354    }
3355
3356    /// The character representation of this [IndentSize].
3357    pub fn char(&self) -> char {
3358        match self.kind {
3359            IndentKind::Space => ' ',
3360            IndentKind::Tab => '\t',
3361        }
3362    }
3363
3364    /// Consumes the current [IndentSize] and returns a new one that has
3365    /// been shrunk or enlarged by the given size along the given direction.
3366    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
3367        match direction {
3368            Ordering::Less => {
3369                if self.kind == size.kind && self.len >= size.len {
3370                    self.len -= size.len;
3371                }
3372            }
3373            Ordering::Equal => {}
3374            Ordering::Greater => {
3375                if self.len == 0 {
3376                    self = size;
3377                } else if self.kind == size.kind {
3378                    self.len += size.len;
3379                }
3380            }
3381        }
3382        self
3383    }
3384}
3385
3386impl Completion {
3387    /// A key that can be used to sort completions when displaying
3388    /// them to the user.
3389    pub fn sort_key(&self) -> (usize, &str) {
3390        let kind_key = match self.lsp_completion.kind {
3391            Some(lsp::CompletionItemKind::VARIABLE) => 0,
3392            _ => 1,
3393        };
3394        (kind_key, &self.label.text[self.label.filter_range.clone()])
3395    }
3396
3397    /// Whether this completion is a snippet.
3398    pub fn is_snippet(&self) -> bool {
3399        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
3400    }
3401}
3402
3403pub(crate) fn contiguous_ranges(
3404    values: impl Iterator<Item = u32>,
3405    max_len: usize,
3406) -> impl Iterator<Item = Range<u32>> {
3407    let mut values = values;
3408    let mut current_range: Option<Range<u32>> = None;
3409    std::iter::from_fn(move || loop {
3410        if let Some(value) = values.next() {
3411            if let Some(range) = &mut current_range {
3412                if value == range.end && range.len() < max_len {
3413                    range.end += 1;
3414                    continue;
3415                }
3416            }
3417
3418            let prev_range = current_range.clone();
3419            current_range = Some(value..(value + 1));
3420            if prev_range.is_some() {
3421                return prev_range;
3422            }
3423        } else {
3424            return current_range.take();
3425        }
3426    })
3427}
3428
3429/// Returns the [CharKind] for the given character. When a scope is provided,
3430/// the function checks if the character is considered a word character
3431/// based on the language scope's word character settings.
3432pub fn char_kind(scope: &Option<LanguageScope>, c: char) -> CharKind {
3433    if c.is_whitespace() {
3434        return CharKind::Whitespace;
3435    } else if c.is_alphanumeric() || c == '_' {
3436        return CharKind::Word;
3437    }
3438
3439    if let Some(scope) = scope {
3440        if let Some(characters) = scope.word_characters() {
3441            if characters.contains(&c) {
3442                return CharKind::Word;
3443            }
3444        }
3445    }
3446
3447    CharKind::Punctuation
3448}
3449
3450/// Find all of the ranges of whitespace that occur at the ends of lines
3451/// in the given rope.
3452///
3453/// This could also be done with a regex search, but this implementation
3454/// avoids copying text.
3455pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
3456    let mut ranges = Vec::new();
3457
3458    let mut offset = 0;
3459    let mut prev_chunk_trailing_whitespace_range = 0..0;
3460    for chunk in rope.chunks() {
3461        let mut prev_line_trailing_whitespace_range = 0..0;
3462        for (i, line) in chunk.split('\n').enumerate() {
3463            let line_end_offset = offset + line.len();
3464            let trimmed_line_len = line.trim_end_matches(|c| matches!(c, ' ' | '\t')).len();
3465            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
3466
3467            if i == 0 && trimmed_line_len == 0 {
3468                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
3469            }
3470            if !prev_line_trailing_whitespace_range.is_empty() {
3471                ranges.push(prev_line_trailing_whitespace_range);
3472            }
3473
3474            offset = line_end_offset + 1;
3475            prev_line_trailing_whitespace_range = trailing_whitespace_range;
3476        }
3477
3478        offset -= 1;
3479        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
3480    }
3481
3482    if !prev_chunk_trailing_whitespace_range.is_empty() {
3483        ranges.push(prev_chunk_trailing_whitespace_range);
3484    }
3485
3486    ranges
3487}