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