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