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