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