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