buffer.rs

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