buffer.rs

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