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