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