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