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