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: Option<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        // We want to look at diagnostic spans only when iterating over language-annotated chunks.
2582        let diagnostics = language_aware;
2583        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostics, Some(self))
2584    }
2585
2586    /// Invokes the given callback for each line of text in the given range of the buffer.
2587    /// Uses callback to avoid allocating a string for each line.
2588    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
2589        let mut line = String::new();
2590        let mut row = range.start.row;
2591        for chunk in self
2592            .as_rope()
2593            .chunks_in_range(range.to_offset(self))
2594            .chain(["\n"])
2595        {
2596            for (newline_ix, text) in chunk.split('\n').enumerate() {
2597                if newline_ix > 0 {
2598                    callback(row, &line);
2599                    row += 1;
2600                    line.clear();
2601                }
2602                line.push_str(text);
2603            }
2604        }
2605    }
2606
2607    /// Iterates over every [`SyntaxLayer`] in the buffer.
2608    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
2609        self.syntax.layers_for_range(0..self.len(), &self.text)
2610    }
2611
2612    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
2613        let offset = position.to_offset(self);
2614        self.syntax
2615            .layers_for_range(offset..offset, &self.text)
2616            .filter(|l| l.node().end_byte() > offset)
2617            .last()
2618    }
2619
2620    /// Returns the main [Language]
2621    pub fn language(&self) -> Option<&Arc<Language>> {
2622        self.language.as_ref()
2623    }
2624
2625    /// Returns the [Language] at the given location.
2626    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
2627        self.syntax_layer_at(position)
2628            .map(|info| info.language)
2629            .or(self.language.as_ref())
2630    }
2631
2632    /// Returns the settings for the language at the given location.
2633    pub fn settings_at<'a, D: ToOffset>(
2634        &self,
2635        position: D,
2636        cx: &'a AppContext,
2637    ) -> &'a LanguageSettings {
2638        language_settings(self.language_at(position), self.file.as_ref(), cx)
2639    }
2640
2641    /// Returns the [LanguageScope] at the given location.
2642    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
2643        let offset = position.to_offset(self);
2644        let mut scope = None;
2645        let mut smallest_range: Option<Range<usize>> = None;
2646
2647        // Use the layer that has the smallest node intersecting the given point.
2648        for layer in self.syntax.layers_for_range(offset..offset, &self.text) {
2649            let mut cursor = layer.node().walk();
2650
2651            let mut range = None;
2652            loop {
2653                let child_range = cursor.node().byte_range();
2654                if !child_range.to_inclusive().contains(&offset) {
2655                    break;
2656                }
2657
2658                range = Some(child_range);
2659                if cursor.goto_first_child_for_byte(offset).is_none() {
2660                    break;
2661                }
2662            }
2663
2664            if let Some(range) = range {
2665                if smallest_range
2666                    .as_ref()
2667                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
2668                {
2669                    smallest_range = Some(range);
2670                    scope = Some(LanguageScope {
2671                        language: layer.language.clone(),
2672                        override_id: layer.override_id(offset, &self.text),
2673                    });
2674                }
2675            }
2676        }
2677
2678        scope.or_else(|| {
2679            self.language.clone().map(|language| LanguageScope {
2680                language,
2681                override_id: None,
2682            })
2683        })
2684    }
2685
2686    /// Returns a tuple of the range and character kind of the word
2687    /// surrounding the given position.
2688    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2689        let mut start = start.to_offset(self);
2690        let mut end = start;
2691        let mut next_chars = self.chars_at(start).peekable();
2692        let mut prev_chars = self.reversed_chars_at(start).peekable();
2693
2694        let scope = self.language_scope_at(start);
2695        let kind = |c| char_kind(&scope, c);
2696        let word_kind = cmp::max(
2697            prev_chars.peek().copied().map(kind),
2698            next_chars.peek().copied().map(kind),
2699        );
2700
2701        for ch in prev_chars {
2702            if Some(kind(ch)) == word_kind && ch != '\n' {
2703                start -= ch.len_utf8();
2704            } else {
2705                break;
2706            }
2707        }
2708
2709        for ch in next_chars {
2710            if Some(kind(ch)) == word_kind && ch != '\n' {
2711                end += ch.len_utf8();
2712            } else {
2713                break;
2714            }
2715        }
2716
2717        (start..end, word_kind)
2718    }
2719
2720    /// Returns the range for the closes syntax node enclosing the given range.
2721    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2722        let range = range.start.to_offset(self)..range.end.to_offset(self);
2723        let mut result: Option<Range<usize>> = None;
2724        'outer: for layer in self.syntax.layers_for_range(range.clone(), &self.text) {
2725            let mut cursor = layer.node().walk();
2726
2727            // Descend to the first leaf that touches the start of the range,
2728            // and if the range is non-empty, extends beyond the start.
2729            while cursor.goto_first_child_for_byte(range.start).is_some() {
2730                if !range.is_empty() && cursor.node().end_byte() == range.start {
2731                    cursor.goto_next_sibling();
2732                }
2733            }
2734
2735            // Ascend to the smallest ancestor that strictly contains the range.
2736            loop {
2737                let node_range = cursor.node().byte_range();
2738                if node_range.start <= range.start
2739                    && node_range.end >= range.end
2740                    && node_range.len() > range.len()
2741                {
2742                    break;
2743                }
2744                if !cursor.goto_parent() {
2745                    continue 'outer;
2746                }
2747            }
2748
2749            let left_node = cursor.node();
2750            let mut layer_result = left_node.byte_range();
2751
2752            // For an empty range, try to find another node immediately to the right of the range.
2753            if left_node.end_byte() == range.start {
2754                let mut right_node = None;
2755                while !cursor.goto_next_sibling() {
2756                    if !cursor.goto_parent() {
2757                        break;
2758                    }
2759                }
2760
2761                while cursor.node().start_byte() == range.start {
2762                    right_node = Some(cursor.node());
2763                    if !cursor.goto_first_child() {
2764                        break;
2765                    }
2766                }
2767
2768                // If there is a candidate node on both sides of the (empty) range, then
2769                // decide between the two by favoring a named node over an anonymous token.
2770                // If both nodes are the same in that regard, favor the right one.
2771                if let Some(right_node) = right_node {
2772                    if right_node.is_named() || !left_node.is_named() {
2773                        layer_result = right_node.byte_range();
2774                    }
2775                }
2776            }
2777
2778            if let Some(previous_result) = &result {
2779                if previous_result.len() < layer_result.len() {
2780                    continue;
2781                }
2782            }
2783            result = Some(layer_result);
2784        }
2785
2786        result
2787    }
2788
2789    /// Returns the outline for the buffer.
2790    ///
2791    /// This method allows passing an optional [SyntaxTheme] to
2792    /// syntax-highlight the returned symbols.
2793    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2794        self.outline_items_containing(0..self.len(), true, theme)
2795            .map(Outline::new)
2796    }
2797
2798    /// Returns all the symbols that contain the given position.
2799    ///
2800    /// This method allows passing an optional [SyntaxTheme] to
2801    /// syntax-highlight the returned symbols.
2802    pub fn symbols_containing<T: ToOffset>(
2803        &self,
2804        position: T,
2805        theme: Option<&SyntaxTheme>,
2806    ) -> Option<Vec<OutlineItem<Anchor>>> {
2807        let position = position.to_offset(self);
2808        let mut items = self.outline_items_containing(
2809            position.saturating_sub(1)..self.len().min(position + 1),
2810            false,
2811            theme,
2812        )?;
2813        let mut prev_depth = None;
2814        items.retain(|item| {
2815            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
2816            prev_depth = Some(item.depth);
2817            result
2818        });
2819        Some(items)
2820    }
2821
2822    pub fn outline_items_containing<T: ToOffset>(
2823        &self,
2824        range: Range<T>,
2825        include_extra_context: bool,
2826        theme: Option<&SyntaxTheme>,
2827    ) -> Option<Vec<OutlineItem<Anchor>>> {
2828        let range = range.to_offset(self);
2829        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2830            grammar.outline_config.as_ref().map(|c| &c.query)
2831        });
2832        let configs = matches
2833            .grammars()
2834            .iter()
2835            .map(|g| g.outline_config.as_ref().unwrap())
2836            .collect::<Vec<_>>();
2837
2838        let mut items = Vec::new();
2839        let mut annotation_row_ranges: Vec<Range<u32>> = Vec::new();
2840        while let Some(mat) = matches.peek() {
2841            let config = &configs[mat.grammar_index];
2842            if let Some(item) =
2843                self.next_outline_item(config, &mat, &range, include_extra_context, theme)
2844            {
2845                items.push(item);
2846            } else if let Some(capture) = mat
2847                .captures
2848                .iter()
2849                .find(|capture| Some(capture.index) == config.annotation_capture_ix)
2850            {
2851                let capture_range = capture.node.start_position()..capture.node.end_position();
2852                let mut capture_row_range =
2853                    capture_range.start.row as u32..capture_range.end.row as u32;
2854                if capture_range.end.row > capture_range.start.row && capture_range.end.column == 0
2855                {
2856                    capture_row_range.end -= 1;
2857                }
2858                if let Some(last_row_range) = annotation_row_ranges.last_mut() {
2859                    if last_row_range.end >= capture_row_range.start.saturating_sub(1) {
2860                        last_row_range.end = capture_row_range.end;
2861                    } else {
2862                        annotation_row_ranges.push(capture_row_range);
2863                    }
2864                } else {
2865                    annotation_row_ranges.push(capture_row_range);
2866                }
2867            }
2868            matches.advance();
2869        }
2870
2871        items.sort_by_key(|item| (item.range.start, Reverse(item.range.end)));
2872
2873        // Assign depths based on containment relationships and convert to anchors.
2874        let mut item_ends_stack = Vec::<Point>::new();
2875        let mut anchor_items = Vec::new();
2876        let mut annotation_row_ranges = annotation_row_ranges.into_iter().peekable();
2877        for item in items {
2878            while let Some(last_end) = item_ends_stack.last().copied() {
2879                if last_end < item.range.end {
2880                    item_ends_stack.pop();
2881                } else {
2882                    break;
2883                }
2884            }
2885
2886            let mut annotation_row_range = None;
2887            while let Some(next_annotation_row_range) = annotation_row_ranges.peek() {
2888                let row_preceding_item = item.range.start.row.saturating_sub(1);
2889                if next_annotation_row_range.end < row_preceding_item {
2890                    annotation_row_ranges.next();
2891                } else {
2892                    if next_annotation_row_range.end == row_preceding_item {
2893                        annotation_row_range = Some(next_annotation_row_range.clone());
2894                        annotation_row_ranges.next();
2895                    }
2896                    break;
2897                }
2898            }
2899
2900            anchor_items.push(OutlineItem {
2901                depth: item_ends_stack.len(),
2902                range: self.anchor_after(item.range.start)..self.anchor_before(item.range.end),
2903                text: item.text,
2904                highlight_ranges: item.highlight_ranges,
2905                name_ranges: item.name_ranges,
2906                body_range: item.body_range.map(|body_range| {
2907                    self.anchor_after(body_range.start)..self.anchor_before(body_range.end)
2908                }),
2909                annotation_range: annotation_row_range.map(|annotation_range| {
2910                    self.anchor_after(Point::new(annotation_range.start, 0))
2911                        ..self.anchor_before(Point::new(
2912                            annotation_range.end,
2913                            self.line_len(annotation_range.end),
2914                        ))
2915                }),
2916            });
2917            item_ends_stack.push(item.range.end);
2918        }
2919
2920        Some(anchor_items)
2921    }
2922
2923    fn next_outline_item(
2924        &self,
2925        config: &OutlineConfig,
2926        mat: &SyntaxMapMatch,
2927        range: &Range<usize>,
2928        include_extra_context: bool,
2929        theme: Option<&SyntaxTheme>,
2930    ) -> Option<OutlineItem<Point>> {
2931        let item_node = mat.captures.iter().find_map(|cap| {
2932            if cap.index == config.item_capture_ix {
2933                Some(cap.node)
2934            } else {
2935                None
2936            }
2937        })?;
2938
2939        let item_byte_range = item_node.byte_range();
2940        if item_byte_range.end < range.start || item_byte_range.start > range.end {
2941            return None;
2942        }
2943        let item_point_range = Point::from_ts_point(item_node.start_position())
2944            ..Point::from_ts_point(item_node.end_position());
2945
2946        let mut open_point = None;
2947        let mut close_point = None;
2948        let mut buffer_ranges = Vec::new();
2949        for capture in mat.captures {
2950            let node_is_name;
2951            if capture.index == config.name_capture_ix {
2952                node_is_name = true;
2953            } else if Some(capture.index) == config.context_capture_ix
2954                || (Some(capture.index) == config.extra_context_capture_ix && include_extra_context)
2955            {
2956                node_is_name = false;
2957            } else {
2958                if Some(capture.index) == config.open_capture_ix {
2959                    open_point = Some(Point::from_ts_point(capture.node.end_position()));
2960                } else if Some(capture.index) == config.close_capture_ix {
2961                    close_point = Some(Point::from_ts_point(capture.node.start_position()));
2962                }
2963
2964                continue;
2965            }
2966
2967            let mut range = capture.node.start_byte()..capture.node.end_byte();
2968            let start = capture.node.start_position();
2969            if capture.node.end_position().row > start.row {
2970                range.end = range.start + self.line_len(start.row as u32) as usize - start.column;
2971            }
2972
2973            if !range.is_empty() {
2974                buffer_ranges.push((range, node_is_name));
2975            }
2976        }
2977        if buffer_ranges.is_empty() {
2978            return None;
2979        }
2980        let mut text = String::new();
2981        let mut highlight_ranges = Vec::new();
2982        let mut name_ranges = Vec::new();
2983        let mut chunks = self.chunks(
2984            buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
2985            true,
2986        );
2987        let mut last_buffer_range_end = 0;
2988        for (buffer_range, is_name) in buffer_ranges {
2989            if !text.is_empty() && buffer_range.start > last_buffer_range_end {
2990                text.push(' ');
2991            }
2992            last_buffer_range_end = buffer_range.end;
2993            if is_name {
2994                let mut start = text.len();
2995                let end = start + buffer_range.len();
2996
2997                // When multiple names are captured, then the matcheable text
2998                // includes the whitespace in between the names.
2999                if !name_ranges.is_empty() {
3000                    start -= 1;
3001                }
3002
3003                name_ranges.push(start..end);
3004            }
3005
3006            let mut offset = buffer_range.start;
3007            chunks.seek(buffer_range.clone());
3008            for mut chunk in chunks.by_ref() {
3009                if chunk.text.len() > buffer_range.end - offset {
3010                    chunk.text = &chunk.text[0..(buffer_range.end - offset)];
3011                    offset = buffer_range.end;
3012                } else {
3013                    offset += chunk.text.len();
3014                }
3015                let style = chunk
3016                    .syntax_highlight_id
3017                    .zip(theme)
3018                    .and_then(|(highlight, theme)| highlight.style(theme));
3019                if let Some(style) = style {
3020                    let start = text.len();
3021                    let end = start + chunk.text.len();
3022                    highlight_ranges.push((start..end, style));
3023                }
3024                text.push_str(chunk.text);
3025                if offset >= buffer_range.end {
3026                    break;
3027                }
3028            }
3029        }
3030
3031        Some(OutlineItem {
3032            depth: 0, // We'll calculate the depth later
3033            range: item_point_range,
3034            text,
3035            highlight_ranges,
3036            name_ranges,
3037            body_range: open_point.zip(close_point).map(|(start, end)| start..end),
3038            annotation_range: None,
3039        })
3040    }
3041
3042    /// For each grammar in the language, runs the provided
3043    /// [tree_sitter::Query] against the given range.
3044    pub fn matches(
3045        &self,
3046        range: Range<usize>,
3047        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
3048    ) -> SyntaxMapMatches {
3049        self.syntax.matches(range, self, query)
3050    }
3051
3052    /// Returns bracket range pairs overlapping or adjacent to `range`
3053    pub fn bracket_ranges<T: ToOffset>(
3054        &self,
3055        range: Range<T>,
3056    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3057        // Find bracket pairs that *inclusively* contain the given range.
3058        let range = range.start.to_offset(self).saturating_sub(1)
3059            ..self.len().min(range.end.to_offset(self) + 1);
3060
3061        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3062            grammar.brackets_config.as_ref().map(|c| &c.query)
3063        });
3064        let configs = matches
3065            .grammars()
3066            .iter()
3067            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
3068            .collect::<Vec<_>>();
3069
3070        iter::from_fn(move || {
3071            while let Some(mat) = matches.peek() {
3072                let mut open = None;
3073                let mut close = None;
3074                let config = &configs[mat.grammar_index];
3075                for capture in mat.captures {
3076                    if capture.index == config.open_capture_ix {
3077                        open = Some(capture.node.byte_range());
3078                    } else if capture.index == config.close_capture_ix {
3079                        close = Some(capture.node.byte_range());
3080                    }
3081                }
3082
3083                matches.advance();
3084
3085                let Some((open, close)) = open.zip(close) else {
3086                    continue;
3087                };
3088
3089                let bracket_range = open.start..=close.end;
3090                if !bracket_range.overlaps(&range) {
3091                    continue;
3092                }
3093
3094                return Some((open, close));
3095            }
3096            None
3097        })
3098    }
3099
3100    /// Returns enclosing bracket ranges containing the given range
3101    pub fn enclosing_bracket_ranges<T: ToOffset>(
3102        &self,
3103        range: Range<T>,
3104    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3105        let range = range.start.to_offset(self)..range.end.to_offset(self);
3106
3107        self.bracket_ranges(range.clone())
3108            .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
3109    }
3110
3111    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3112    ///
3113    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3114    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3115        &self,
3116        range: Range<T>,
3117        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3118    ) -> Option<(Range<usize>, Range<usize>)> {
3119        let range = range.start.to_offset(self)..range.end.to_offset(self);
3120
3121        // Get the ranges of the innermost pair of brackets.
3122        let mut result: Option<(Range<usize>, Range<usize>)> = None;
3123
3124        for (open, close) in self.enclosing_bracket_ranges(range.clone()) {
3125            if let Some(range_filter) = range_filter {
3126                if !range_filter(open.clone(), close.clone()) {
3127                    continue;
3128                }
3129            }
3130
3131            let len = close.end - open.start;
3132
3133            if let Some((existing_open, existing_close)) = &result {
3134                let existing_len = existing_close.end - existing_open.start;
3135                if len > existing_len {
3136                    continue;
3137                }
3138            }
3139
3140            result = Some((open, close));
3141        }
3142
3143        result
3144    }
3145
3146    /// Returns anchor ranges for any matches of the redaction query.
3147    /// The buffer can be associated with multiple languages, and the redaction query associated with each
3148    /// will be run on the relevant section of the buffer.
3149    pub fn redacted_ranges<T: ToOffset>(
3150        &self,
3151        range: Range<T>,
3152    ) -> impl Iterator<Item = Range<usize>> + '_ {
3153        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3154        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3155            grammar
3156                .redactions_config
3157                .as_ref()
3158                .map(|config| &config.query)
3159        });
3160
3161        let configs = syntax_matches
3162            .grammars()
3163            .iter()
3164            .map(|grammar| grammar.redactions_config.as_ref())
3165            .collect::<Vec<_>>();
3166
3167        iter::from_fn(move || {
3168            let redacted_range = syntax_matches
3169                .peek()
3170                .and_then(|mat| {
3171                    configs[mat.grammar_index].and_then(|config| {
3172                        mat.captures
3173                            .iter()
3174                            .find(|capture| capture.index == config.redaction_capture_ix)
3175                    })
3176                })
3177                .map(|mat| mat.node.byte_range());
3178            syntax_matches.advance();
3179            redacted_range
3180        })
3181    }
3182
3183    pub fn injections_intersecting_range<T: ToOffset>(
3184        &self,
3185        range: Range<T>,
3186    ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3187        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3188
3189        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3190            grammar
3191                .injection_config
3192                .as_ref()
3193                .map(|config| &config.query)
3194        });
3195
3196        let configs = syntax_matches
3197            .grammars()
3198            .iter()
3199            .map(|grammar| grammar.injection_config.as_ref())
3200            .collect::<Vec<_>>();
3201
3202        iter::from_fn(move || {
3203            let ranges = syntax_matches.peek().and_then(|mat| {
3204                let config = &configs[mat.grammar_index]?;
3205                let content_capture_range = mat.captures.iter().find_map(|capture| {
3206                    if capture.index == config.content_capture_ix {
3207                        Some(capture.node.byte_range())
3208                    } else {
3209                        None
3210                    }
3211                })?;
3212                let language = self.language_at(content_capture_range.start)?;
3213                Some((content_capture_range, language))
3214            });
3215            syntax_matches.advance();
3216            ranges
3217        })
3218    }
3219
3220    pub fn runnable_ranges(
3221        &self,
3222        range: Range<Anchor>,
3223    ) -> impl Iterator<Item = RunnableRange> + '_ {
3224        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3225
3226        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3227            grammar.runnable_config.as_ref().map(|config| &config.query)
3228        });
3229
3230        let test_configs = syntax_matches
3231            .grammars()
3232            .iter()
3233            .map(|grammar| grammar.runnable_config.as_ref())
3234            .collect::<Vec<_>>();
3235
3236        iter::from_fn(move || loop {
3237            let mat = syntax_matches.peek()?;
3238
3239            let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3240                let mut run_range = None;
3241                let full_range = mat.captures.iter().fold(
3242                    Range {
3243                        start: usize::MAX,
3244                        end: 0,
3245                    },
3246                    |mut acc, next| {
3247                        let byte_range = next.node.byte_range();
3248                        if acc.start > byte_range.start {
3249                            acc.start = byte_range.start;
3250                        }
3251                        if acc.end < byte_range.end {
3252                            acc.end = byte_range.end;
3253                        }
3254                        acc
3255                    },
3256                );
3257                if full_range.start > full_range.end {
3258                    // We did not find a full spanning range of this match.
3259                    return None;
3260                }
3261                let extra_captures: SmallVec<[_; 1]> =
3262                    SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3263                        test_configs
3264                            .extra_captures
3265                            .get(capture.index as usize)
3266                            .cloned()
3267                            .and_then(|tag_name| match tag_name {
3268                                RunnableCapture::Named(name) => {
3269                                    Some((capture.node.byte_range(), name))
3270                                }
3271                                RunnableCapture::Run => {
3272                                    let _ = run_range.insert(capture.node.byte_range());
3273                                    None
3274                                }
3275                            })
3276                    }));
3277                let run_range = run_range?;
3278                let tags = test_configs
3279                    .query
3280                    .property_settings(mat.pattern_index)
3281                    .iter()
3282                    .filter_map(|property| {
3283                        if *property.key == *"tag" {
3284                            property
3285                                .value
3286                                .as_ref()
3287                                .map(|value| RunnableTag(value.to_string().into()))
3288                        } else {
3289                            None
3290                        }
3291                    })
3292                    .collect();
3293                let extra_captures = extra_captures
3294                    .into_iter()
3295                    .map(|(range, name)| {
3296                        (
3297                            name.to_string(),
3298                            self.text_for_range(range.clone()).collect::<String>(),
3299                        )
3300                    })
3301                    .collect();
3302                // All tags should have the same range.
3303                Some(RunnableRange {
3304                    run_range,
3305                    full_range,
3306                    runnable: Runnable {
3307                        tags,
3308                        language: mat.language,
3309                        buffer: self.remote_id(),
3310                    },
3311                    extra_captures,
3312                    buffer_id: self.remote_id(),
3313                })
3314            });
3315
3316            syntax_matches.advance();
3317            if test_range.is_some() {
3318                // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
3319                // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
3320                return test_range;
3321            }
3322        })
3323    }
3324
3325    pub fn indent_guides_in_range(
3326        &self,
3327        range: Range<Anchor>,
3328        ignore_disabled_for_language: bool,
3329        cx: &AppContext,
3330    ) -> Vec<IndentGuide> {
3331        let language_settings = language_settings(self.language(), self.file.as_ref(), cx);
3332        let settings = language_settings.indent_guides;
3333        if !ignore_disabled_for_language && !settings.enabled {
3334            return Vec::new();
3335        }
3336        let tab_size = language_settings.tab_size.get() as u32;
3337
3338        let start_row = range.start.to_point(self).row;
3339        let end_row = range.end.to_point(self).row;
3340        let row_range = start_row..end_row + 1;
3341
3342        let mut row_indents = self.line_indents_in_row_range(row_range.clone());
3343
3344        let mut result_vec = Vec::new();
3345        let mut indent_stack = SmallVec::<[IndentGuide; 8]>::new();
3346
3347        while let Some((first_row, mut line_indent)) = row_indents.next() {
3348            let current_depth = indent_stack.len() as u32;
3349
3350            // When encountering empty, continue until found useful line indent
3351            // then add to the indent stack with the depth found
3352            let mut found_indent = false;
3353            let mut last_row = first_row;
3354            if line_indent.is_line_empty() {
3355                let mut trailing_row = end_row;
3356                while !found_indent {
3357                    let (target_row, new_line_indent) =
3358                        if let Some(display_row) = row_indents.next() {
3359                            display_row
3360                        } else {
3361                            // This means we reached the end of the given range and found empty lines at the end.
3362                            // We need to traverse further until we find a non-empty line to know if we need to add
3363                            // an indent guide for the last visible indent.
3364                            trailing_row += 1;
3365
3366                            const TRAILING_ROW_SEARCH_LIMIT: u32 = 25;
3367                            if trailing_row > self.max_point().row
3368                                || trailing_row > end_row + TRAILING_ROW_SEARCH_LIMIT
3369                            {
3370                                break;
3371                            }
3372                            let new_line_indent = self.line_indent_for_row(trailing_row);
3373                            (trailing_row, new_line_indent)
3374                        };
3375
3376                    if new_line_indent.is_line_empty() {
3377                        continue;
3378                    }
3379                    last_row = target_row.min(end_row);
3380                    line_indent = new_line_indent;
3381                    found_indent = true;
3382                    break;
3383                }
3384            } else {
3385                found_indent = true
3386            }
3387
3388            let depth = if found_indent {
3389                line_indent.len(tab_size) / tab_size
3390                    + ((line_indent.len(tab_size) % tab_size) > 0) as u32
3391            } else {
3392                current_depth
3393            };
3394
3395            if depth < current_depth {
3396                for _ in 0..(current_depth - depth) {
3397                    let mut indent = indent_stack.pop().unwrap();
3398                    if last_row != first_row {
3399                        // In this case, we landed on an empty row, had to seek forward,
3400                        // and discovered that the indent we where on is ending.
3401                        // This means that the last display row must
3402                        // be on line that ends this indent range, so we
3403                        // should display the range up to the first non-empty line
3404                        indent.end_row = first_row.saturating_sub(1);
3405                    }
3406
3407                    result_vec.push(indent)
3408                }
3409            } else if depth > current_depth {
3410                for next_depth in current_depth..depth {
3411                    indent_stack.push(IndentGuide {
3412                        buffer_id: self.remote_id(),
3413                        start_row: first_row,
3414                        end_row: last_row,
3415                        depth: next_depth,
3416                        tab_size,
3417                        settings,
3418                    });
3419                }
3420            }
3421
3422            for indent in indent_stack.iter_mut() {
3423                indent.end_row = last_row;
3424            }
3425        }
3426
3427        result_vec.extend(indent_stack);
3428
3429        result_vec
3430    }
3431
3432    pub async fn enclosing_indent(
3433        &self,
3434        mut buffer_row: BufferRow,
3435    ) -> Option<(Range<BufferRow>, LineIndent)> {
3436        let max_row = self.max_point().row;
3437        if buffer_row >= max_row {
3438            return None;
3439        }
3440
3441        let mut target_indent = self.line_indent_for_row(buffer_row);
3442
3443        // If the current row is at the start of an indented block, we want to return this
3444        // block as the enclosing indent.
3445        if !target_indent.is_line_empty() && buffer_row < max_row {
3446            let next_line_indent = self.line_indent_for_row(buffer_row + 1);
3447            if !next_line_indent.is_line_empty()
3448                && target_indent.raw_len() < next_line_indent.raw_len()
3449            {
3450                target_indent = next_line_indent;
3451                buffer_row += 1;
3452            }
3453        }
3454
3455        const SEARCH_ROW_LIMIT: u32 = 25000;
3456        const SEARCH_WHITESPACE_ROW_LIMIT: u32 = 2500;
3457        const YIELD_INTERVAL: u32 = 100;
3458
3459        let mut accessed_row_counter = 0;
3460
3461        // If there is a blank line at the current row, search for the next non indented lines
3462        if target_indent.is_line_empty() {
3463            let start = buffer_row.saturating_sub(SEARCH_WHITESPACE_ROW_LIMIT);
3464            let end = (max_row + 1).min(buffer_row + SEARCH_WHITESPACE_ROW_LIMIT);
3465
3466            let mut non_empty_line_above = None;
3467            for (row, indent) in self
3468                .text
3469                .reversed_line_indents_in_row_range(start..buffer_row)
3470            {
3471                accessed_row_counter += 1;
3472                if accessed_row_counter == YIELD_INTERVAL {
3473                    accessed_row_counter = 0;
3474                    yield_now().await;
3475                }
3476                if !indent.is_line_empty() {
3477                    non_empty_line_above = Some((row, indent));
3478                    break;
3479                }
3480            }
3481
3482            let mut non_empty_line_below = None;
3483            for (row, indent) in self.text.line_indents_in_row_range((buffer_row + 1)..end) {
3484                accessed_row_counter += 1;
3485                if accessed_row_counter == YIELD_INTERVAL {
3486                    accessed_row_counter = 0;
3487                    yield_now().await;
3488                }
3489                if !indent.is_line_empty() {
3490                    non_empty_line_below = Some((row, indent));
3491                    break;
3492                }
3493            }
3494
3495            let (row, indent) = match (non_empty_line_above, non_empty_line_below) {
3496                (Some((above_row, above_indent)), Some((below_row, below_indent))) => {
3497                    if above_indent.raw_len() >= below_indent.raw_len() {
3498                        (above_row, above_indent)
3499                    } else {
3500                        (below_row, below_indent)
3501                    }
3502                }
3503                (Some(above), None) => above,
3504                (None, Some(below)) => below,
3505                _ => return None,
3506            };
3507
3508            target_indent = indent;
3509            buffer_row = row;
3510        }
3511
3512        let start = buffer_row.saturating_sub(SEARCH_ROW_LIMIT);
3513        let end = (max_row + 1).min(buffer_row + SEARCH_ROW_LIMIT);
3514
3515        let mut start_indent = None;
3516        for (row, indent) in self
3517            .text
3518            .reversed_line_indents_in_row_range(start..buffer_row)
3519        {
3520            accessed_row_counter += 1;
3521            if accessed_row_counter == YIELD_INTERVAL {
3522                accessed_row_counter = 0;
3523                yield_now().await;
3524            }
3525            if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
3526                start_indent = Some((row, indent));
3527                break;
3528            }
3529        }
3530        let (start_row, start_indent_size) = start_indent?;
3531
3532        let mut end_indent = (end, None);
3533        for (row, indent) in self.text.line_indents_in_row_range((buffer_row + 1)..end) {
3534            accessed_row_counter += 1;
3535            if accessed_row_counter == YIELD_INTERVAL {
3536                accessed_row_counter = 0;
3537                yield_now().await;
3538            }
3539            if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
3540                end_indent = (row.saturating_sub(1), Some(indent));
3541                break;
3542            }
3543        }
3544        let (end_row, end_indent_size) = end_indent;
3545
3546        let indent = if let Some(end_indent_size) = end_indent_size {
3547            if start_indent_size.raw_len() > end_indent_size.raw_len() {
3548                start_indent_size
3549            } else {
3550                end_indent_size
3551            }
3552        } else {
3553            start_indent_size
3554        };
3555
3556        Some((start_row..end_row, indent))
3557    }
3558
3559    /// Returns selections for remote peers intersecting the given range.
3560    #[allow(clippy::type_complexity)]
3561    pub fn selections_in_range(
3562        &self,
3563        range: Range<Anchor>,
3564        include_local: bool,
3565    ) -> impl Iterator<
3566        Item = (
3567            ReplicaId,
3568            bool,
3569            CursorShape,
3570            impl Iterator<Item = &Selection<Anchor>> + '_,
3571        ),
3572    > + '_ {
3573        self.remote_selections
3574            .iter()
3575            .filter(move |(replica_id, set)| {
3576                (include_local || **replica_id != self.text.replica_id())
3577                    && !set.selections.is_empty()
3578            })
3579            .map(move |(replica_id, set)| {
3580                let start_ix = match set.selections.binary_search_by(|probe| {
3581                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
3582                }) {
3583                    Ok(ix) | Err(ix) => ix,
3584                };
3585                let end_ix = match set.selections.binary_search_by(|probe| {
3586                    probe.start.cmp(&range.end, self).then(Ordering::Less)
3587                }) {
3588                    Ok(ix) | Err(ix) => ix,
3589                };
3590
3591                (
3592                    *replica_id,
3593                    set.line_mode,
3594                    set.cursor_shape,
3595                    set.selections[start_ix..end_ix].iter(),
3596                )
3597            })
3598    }
3599
3600    /// Whether the buffer contains any git changes.
3601    pub fn has_git_diff(&self) -> bool {
3602        !self.git_diff.is_empty()
3603    }
3604
3605    /// Returns all the Git diff hunks intersecting the given
3606    /// row range.
3607    pub fn git_diff_hunks_in_row_range(
3608        &self,
3609        range: Range<BufferRow>,
3610    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3611        self.git_diff.hunks_in_row_range(range, self)
3612    }
3613
3614    /// Returns all the Git diff hunks intersecting the given
3615    /// range.
3616    pub fn git_diff_hunks_intersecting_range(
3617        &self,
3618        range: Range<Anchor>,
3619    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3620        self.git_diff.hunks_intersecting_range(range, self)
3621    }
3622
3623    /// Returns all the Git diff hunks intersecting the given
3624    /// range, in reverse order.
3625    pub fn git_diff_hunks_intersecting_range_rev(
3626        &self,
3627        range: Range<Anchor>,
3628    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3629        self.git_diff.hunks_intersecting_range_rev(range, self)
3630    }
3631
3632    /// Returns if the buffer contains any diagnostics.
3633    pub fn has_diagnostics(&self) -> bool {
3634        !self.diagnostics.is_empty()
3635    }
3636
3637    /// Returns all the diagnostics intersecting the given range.
3638    pub fn diagnostics_in_range<'a, T, O>(
3639        &'a self,
3640        search_range: Range<T>,
3641        reversed: bool,
3642    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3643    where
3644        T: 'a + Clone + ToOffset,
3645        O: 'a + FromAnchor + Ord,
3646    {
3647        let mut iterators: Vec<_> = self
3648            .diagnostics
3649            .iter()
3650            .map(|(_, collection)| {
3651                collection
3652                    .range::<T, O>(search_range.clone(), self, true, reversed)
3653                    .peekable()
3654            })
3655            .collect();
3656
3657        std::iter::from_fn(move || {
3658            let (next_ix, _) = iterators
3659                .iter_mut()
3660                .enumerate()
3661                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
3662                .min_by(|(_, a), (_, b)| {
3663                    let cmp = a
3664                        .range
3665                        .start
3666                        .cmp(&b.range.start)
3667                        // when range is equal, sort by diagnostic severity
3668                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
3669                        // and stabilize order with group_id
3670                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
3671                    if reversed {
3672                        cmp.reverse()
3673                    } else {
3674                        cmp
3675                    }
3676                })?;
3677            iterators[next_ix].next()
3678        })
3679    }
3680
3681    /// Returns all the diagnostic groups associated with the given
3682    /// language server id. If no language server id is provided,
3683    /// all diagnostics groups are returned.
3684    pub fn diagnostic_groups(
3685        &self,
3686        language_server_id: Option<LanguageServerId>,
3687    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
3688        let mut groups = Vec::new();
3689
3690        if let Some(language_server_id) = language_server_id {
3691            if let Ok(ix) = self
3692                .diagnostics
3693                .binary_search_by_key(&language_server_id, |e| e.0)
3694            {
3695                self.diagnostics[ix]
3696                    .1
3697                    .groups(language_server_id, &mut groups, self);
3698            }
3699        } else {
3700            for (language_server_id, diagnostics) in self.diagnostics.iter() {
3701                diagnostics.groups(*language_server_id, &mut groups, self);
3702            }
3703        }
3704
3705        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
3706            let a_start = &group_a.entries[group_a.primary_ix].range.start;
3707            let b_start = &group_b.entries[group_b.primary_ix].range.start;
3708            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
3709        });
3710
3711        groups
3712    }
3713
3714    /// Returns an iterator over the diagnostics for the given group.
3715    pub fn diagnostic_group<'a, O>(
3716        &'a self,
3717        group_id: usize,
3718    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3719    where
3720        O: 'a + FromAnchor,
3721    {
3722        self.diagnostics
3723            .iter()
3724            .flat_map(move |(_, set)| set.group(group_id, self))
3725    }
3726
3727    /// An integer version number that accounts for all updates besides
3728    /// the buffer's text itself (which is versioned via a version vector).
3729    pub fn non_text_state_update_count(&self) -> usize {
3730        self.non_text_state_update_count
3731    }
3732
3733    /// Returns a snapshot of underlying file.
3734    pub fn file(&self) -> Option<&Arc<dyn File>> {
3735        self.file.as_ref()
3736    }
3737
3738    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
3739    pub fn resolve_file_path(&self, cx: &AppContext, include_root: bool) -> Option<PathBuf> {
3740        if let Some(file) = self.file() {
3741            if file.path().file_name().is_none() || include_root {
3742                Some(file.full_path(cx))
3743            } else {
3744                Some(file.path().to_path_buf())
3745            }
3746        } else {
3747            None
3748        }
3749    }
3750}
3751
3752fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
3753    indent_size_for_text(text.chars_at(Point::new(row, 0)))
3754}
3755
3756fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
3757    let mut result = IndentSize::spaces(0);
3758    for c in text {
3759        let kind = match c {
3760            ' ' => IndentKind::Space,
3761            '\t' => IndentKind::Tab,
3762            _ => break,
3763        };
3764        if result.len == 0 {
3765            result.kind = kind;
3766        }
3767        result.len += 1;
3768    }
3769    result
3770}
3771
3772impl Clone for BufferSnapshot {
3773    fn clone(&self) -> Self {
3774        Self {
3775            text: self.text.clone(),
3776            git_diff: self.git_diff.clone(),
3777            syntax: self.syntax.clone(),
3778            file: self.file.clone(),
3779            remote_selections: self.remote_selections.clone(),
3780            diagnostics: self.diagnostics.clone(),
3781            language: self.language.clone(),
3782            non_text_state_update_count: self.non_text_state_update_count,
3783        }
3784    }
3785}
3786
3787impl Deref for BufferSnapshot {
3788    type Target = text::BufferSnapshot;
3789
3790    fn deref(&self) -> &Self::Target {
3791        &self.text
3792    }
3793}
3794
3795unsafe impl<'a> Send for BufferChunks<'a> {}
3796
3797impl<'a> BufferChunks<'a> {
3798    pub(crate) fn new(
3799        text: &'a Rope,
3800        range: Range<usize>,
3801        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
3802        diagnostics: bool,
3803        buffer_snapshot: Option<&'a BufferSnapshot>,
3804    ) -> Self {
3805        let mut highlights = None;
3806        if let Some((captures, highlight_maps)) = syntax {
3807            highlights = Some(BufferChunkHighlights {
3808                captures,
3809                next_capture: None,
3810                stack: Default::default(),
3811                highlight_maps,
3812            })
3813        }
3814
3815        let diagnostic_endpoints = diagnostics.then(|| Vec::new().into_iter().peekable());
3816        let chunks = text.chunks_in_range(range.clone());
3817
3818        let mut this = BufferChunks {
3819            range,
3820            buffer_snapshot,
3821            chunks,
3822            diagnostic_endpoints,
3823            error_depth: 0,
3824            warning_depth: 0,
3825            information_depth: 0,
3826            hint_depth: 0,
3827            unnecessary_depth: 0,
3828            highlights,
3829        };
3830        this.initialize_diagnostic_endpoints();
3831        this
3832    }
3833
3834    /// Seeks to the given byte offset in the buffer.
3835    pub fn seek(&mut self, range: Range<usize>) {
3836        let old_range = std::mem::replace(&mut self.range, range.clone());
3837        self.chunks.set_range(self.range.clone());
3838        if let Some(highlights) = self.highlights.as_mut() {
3839            if old_range.start >= self.range.start && old_range.end <= self.range.end {
3840                // Reuse existing highlights stack, as the new range is a subrange of the old one.
3841                highlights
3842                    .stack
3843                    .retain(|(end_offset, _)| *end_offset > range.start);
3844                if let Some(capture) = &highlights.next_capture {
3845                    if range.start >= capture.node.start_byte() {
3846                        let next_capture_end = capture.node.end_byte();
3847                        if range.start < next_capture_end {
3848                            highlights.stack.push((
3849                                next_capture_end,
3850                                highlights.highlight_maps[capture.grammar_index].get(capture.index),
3851                            ));
3852                        }
3853                        highlights.next_capture.take();
3854                    }
3855                }
3856            } else if let Some(snapshot) = self.buffer_snapshot {
3857                let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
3858                *highlights = BufferChunkHighlights {
3859                    captures,
3860                    next_capture: None,
3861                    stack: Default::default(),
3862                    highlight_maps,
3863                };
3864            } else {
3865                // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
3866                // Seeking such BufferChunks is not supported.
3867                debug_assert!(false, "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot");
3868            }
3869
3870            highlights.captures.set_byte_range(self.range.clone());
3871            self.initialize_diagnostic_endpoints();
3872        }
3873    }
3874
3875    fn initialize_diagnostic_endpoints(&mut self) {
3876        if let Some(diagnostics) = self.diagnostic_endpoints.as_mut() {
3877            if let Some(buffer) = self.buffer_snapshot {
3878                let mut diagnostic_endpoints = Vec::new();
3879                for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
3880                    diagnostic_endpoints.push(DiagnosticEndpoint {
3881                        offset: entry.range.start,
3882                        is_start: true,
3883                        severity: entry.diagnostic.severity,
3884                        is_unnecessary: entry.diagnostic.is_unnecessary,
3885                    });
3886                    diagnostic_endpoints.push(DiagnosticEndpoint {
3887                        offset: entry.range.end,
3888                        is_start: false,
3889                        severity: entry.diagnostic.severity,
3890                        is_unnecessary: entry.diagnostic.is_unnecessary,
3891                    });
3892                }
3893                diagnostic_endpoints
3894                    .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
3895                *diagnostics = diagnostic_endpoints.into_iter().peekable();
3896            }
3897        }
3898    }
3899
3900    /// The current byte offset in the buffer.
3901    pub fn offset(&self) -> usize {
3902        self.range.start
3903    }
3904
3905    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
3906        let depth = match endpoint.severity {
3907            DiagnosticSeverity::ERROR => &mut self.error_depth,
3908            DiagnosticSeverity::WARNING => &mut self.warning_depth,
3909            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
3910            DiagnosticSeverity::HINT => &mut self.hint_depth,
3911            _ => return,
3912        };
3913        if endpoint.is_start {
3914            *depth += 1;
3915        } else {
3916            *depth -= 1;
3917        }
3918
3919        if endpoint.is_unnecessary {
3920            if endpoint.is_start {
3921                self.unnecessary_depth += 1;
3922            } else {
3923                self.unnecessary_depth -= 1;
3924            }
3925        }
3926    }
3927
3928    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
3929        if self.error_depth > 0 {
3930            Some(DiagnosticSeverity::ERROR)
3931        } else if self.warning_depth > 0 {
3932            Some(DiagnosticSeverity::WARNING)
3933        } else if self.information_depth > 0 {
3934            Some(DiagnosticSeverity::INFORMATION)
3935        } else if self.hint_depth > 0 {
3936            Some(DiagnosticSeverity::HINT)
3937        } else {
3938            None
3939        }
3940    }
3941
3942    fn current_code_is_unnecessary(&self) -> bool {
3943        self.unnecessary_depth > 0
3944    }
3945}
3946
3947impl<'a> Iterator for BufferChunks<'a> {
3948    type Item = Chunk<'a>;
3949
3950    fn next(&mut self) -> Option<Self::Item> {
3951        let mut next_capture_start = usize::MAX;
3952        let mut next_diagnostic_endpoint = usize::MAX;
3953
3954        if let Some(highlights) = self.highlights.as_mut() {
3955            while let Some((parent_capture_end, _)) = highlights.stack.last() {
3956                if *parent_capture_end <= self.range.start {
3957                    highlights.stack.pop();
3958                } else {
3959                    break;
3960                }
3961            }
3962
3963            if highlights.next_capture.is_none() {
3964                highlights.next_capture = highlights.captures.next();
3965            }
3966
3967            while let Some(capture) = highlights.next_capture.as_ref() {
3968                if self.range.start < capture.node.start_byte() {
3969                    next_capture_start = capture.node.start_byte();
3970                    break;
3971                } else {
3972                    let highlight_id =
3973                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
3974                    highlights
3975                        .stack
3976                        .push((capture.node.end_byte(), highlight_id));
3977                    highlights.next_capture = highlights.captures.next();
3978                }
3979            }
3980        }
3981
3982        let mut diagnostic_endpoints = std::mem::take(&mut self.diagnostic_endpoints);
3983        if let Some(diagnostic_endpoints) = diagnostic_endpoints.as_mut() {
3984            while let Some(endpoint) = diagnostic_endpoints.peek().copied() {
3985                if endpoint.offset <= self.range.start {
3986                    self.update_diagnostic_depths(endpoint);
3987                    diagnostic_endpoints.next();
3988                } else {
3989                    next_diagnostic_endpoint = endpoint.offset;
3990                    break;
3991                }
3992            }
3993        }
3994        self.diagnostic_endpoints = diagnostic_endpoints;
3995
3996        if let Some(chunk) = self.chunks.peek() {
3997            let chunk_start = self.range.start;
3998            let mut chunk_end = (self.chunks.offset() + chunk.len())
3999                .min(next_capture_start)
4000                .min(next_diagnostic_endpoint);
4001            let mut highlight_id = None;
4002            if let Some(highlights) = self.highlights.as_ref() {
4003                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
4004                    chunk_end = chunk_end.min(*parent_capture_end);
4005                    highlight_id = Some(*parent_highlight_id);
4006                }
4007            }
4008
4009            let slice =
4010                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
4011            self.range.start = chunk_end;
4012            if self.range.start == self.chunks.offset() + chunk.len() {
4013                self.chunks.next().unwrap();
4014            }
4015
4016            Some(Chunk {
4017                text: slice,
4018                syntax_highlight_id: highlight_id,
4019                diagnostic_severity: self.current_diagnostic_severity(),
4020                is_unnecessary: self.current_code_is_unnecessary(),
4021                ..Default::default()
4022            })
4023        } else {
4024            None
4025        }
4026    }
4027}
4028
4029impl operation_queue::Operation for Operation {
4030    fn lamport_timestamp(&self) -> clock::Lamport {
4031        match self {
4032            Operation::Buffer(_) => {
4033                unreachable!("buffer operations should never be deferred at this layer")
4034            }
4035            Operation::UpdateDiagnostics {
4036                lamport_timestamp, ..
4037            }
4038            | Operation::UpdateSelections {
4039                lamport_timestamp, ..
4040            }
4041            | Operation::UpdateCompletionTriggers {
4042                lamport_timestamp, ..
4043            } => *lamport_timestamp,
4044        }
4045    }
4046}
4047
4048impl Default for Diagnostic {
4049    fn default() -> Self {
4050        Self {
4051            source: Default::default(),
4052            code: None,
4053            severity: DiagnosticSeverity::ERROR,
4054            message: Default::default(),
4055            group_id: 0,
4056            is_primary: false,
4057            is_disk_based: false,
4058            is_unnecessary: false,
4059            data: None,
4060        }
4061    }
4062}
4063
4064impl IndentSize {
4065    /// Returns an [IndentSize] representing the given spaces.
4066    pub fn spaces(len: u32) -> Self {
4067        Self {
4068            len,
4069            kind: IndentKind::Space,
4070        }
4071    }
4072
4073    /// Returns an [IndentSize] representing a tab.
4074    pub fn tab() -> Self {
4075        Self {
4076            len: 1,
4077            kind: IndentKind::Tab,
4078        }
4079    }
4080
4081    /// An iterator over the characters represented by this [IndentSize].
4082    pub fn chars(&self) -> impl Iterator<Item = char> {
4083        iter::repeat(self.char()).take(self.len as usize)
4084    }
4085
4086    /// The character representation of this [IndentSize].
4087    pub fn char(&self) -> char {
4088        match self.kind {
4089            IndentKind::Space => ' ',
4090            IndentKind::Tab => '\t',
4091        }
4092    }
4093
4094    /// Consumes the current [IndentSize] and returns a new one that has
4095    /// been shrunk or enlarged by the given size along the given direction.
4096    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4097        match direction {
4098            Ordering::Less => {
4099                if self.kind == size.kind && self.len >= size.len {
4100                    self.len -= size.len;
4101                }
4102            }
4103            Ordering::Equal => {}
4104            Ordering::Greater => {
4105                if self.len == 0 {
4106                    self = size;
4107                } else if self.kind == size.kind {
4108                    self.len += size.len;
4109                }
4110            }
4111        }
4112        self
4113    }
4114}
4115
4116#[cfg(any(test, feature = "test-support"))]
4117pub struct TestFile {
4118    pub path: Arc<Path>,
4119    pub root_name: String,
4120}
4121
4122#[cfg(any(test, feature = "test-support"))]
4123impl File for TestFile {
4124    fn path(&self) -> &Arc<Path> {
4125        &self.path
4126    }
4127
4128    fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
4129        PathBuf::from(&self.root_name).join(self.path.as_ref())
4130    }
4131
4132    fn as_local(&self) -> Option<&dyn LocalFile> {
4133        None
4134    }
4135
4136    fn mtime(&self) -> Option<SystemTime> {
4137        unimplemented!()
4138    }
4139
4140    fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
4141        self.path().file_name().unwrap_or(self.root_name.as_ref())
4142    }
4143
4144    fn worktree_id(&self) -> usize {
4145        0
4146    }
4147
4148    fn is_deleted(&self) -> bool {
4149        unimplemented!()
4150    }
4151
4152    fn as_any(&self) -> &dyn std::any::Any {
4153        unimplemented!()
4154    }
4155
4156    fn to_proto(&self, _: &AppContext) -> rpc::proto::File {
4157        unimplemented!()
4158    }
4159
4160    fn is_private(&self) -> bool {
4161        false
4162    }
4163}
4164
4165pub(crate) fn contiguous_ranges(
4166    values: impl Iterator<Item = u32>,
4167    max_len: usize,
4168) -> impl Iterator<Item = Range<u32>> {
4169    let mut values = values;
4170    let mut current_range: Option<Range<u32>> = None;
4171    std::iter::from_fn(move || loop {
4172        if let Some(value) = values.next() {
4173            if let Some(range) = &mut current_range {
4174                if value == range.end && range.len() < max_len {
4175                    range.end += 1;
4176                    continue;
4177                }
4178            }
4179
4180            let prev_range = current_range.clone();
4181            current_range = Some(value..(value + 1));
4182            if prev_range.is_some() {
4183                return prev_range;
4184            }
4185        } else {
4186            return current_range.take();
4187        }
4188    })
4189}
4190
4191/// Returns the [CharKind] for the given character. When a scope is provided,
4192/// the function checks if the character is considered a word character
4193/// based on the language scope's word character settings.
4194pub fn char_kind(scope: &Option<LanguageScope>, c: char) -> CharKind {
4195    if c.is_whitespace() {
4196        return CharKind::Whitespace;
4197    } else if c.is_alphanumeric() || c == '_' {
4198        return CharKind::Word;
4199    }
4200
4201    if let Some(scope) = scope {
4202        if let Some(characters) = scope.word_characters() {
4203            if characters.contains(&c) {
4204                return CharKind::Word;
4205            }
4206        }
4207    }
4208
4209    CharKind::Punctuation
4210}
4211
4212/// Find all of the ranges of whitespace that occur at the ends of lines
4213/// in the given rope.
4214///
4215/// This could also be done with a regex search, but this implementation
4216/// avoids copying text.
4217pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4218    let mut ranges = Vec::new();
4219
4220    let mut offset = 0;
4221    let mut prev_chunk_trailing_whitespace_range = 0..0;
4222    for chunk in rope.chunks() {
4223        let mut prev_line_trailing_whitespace_range = 0..0;
4224        for (i, line) in chunk.split('\n').enumerate() {
4225            let line_end_offset = offset + line.len();
4226            let trimmed_line_len = line.trim_end_matches(|c| matches!(c, ' ' | '\t')).len();
4227            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4228
4229            if i == 0 && trimmed_line_len == 0 {
4230                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4231            }
4232            if !prev_line_trailing_whitespace_range.is_empty() {
4233                ranges.push(prev_line_trailing_whitespace_range);
4234            }
4235
4236            offset = line_end_offset + 1;
4237            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4238        }
4239
4240        offset -= 1;
4241        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4242    }
4243
4244    if !prev_chunk_trailing_whitespace_range.is_empty() {
4245        ranges.push(prev_chunk_trailing_whitespace_range);
4246    }
4247
4248    ranges
4249}