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