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