buffer.rs

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