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