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