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