buffer.rs

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