buffer.rs

   1pub use crate::{
   2    diagnostic_set::DiagnosticSet,
   3    highlight_map::{HighlightId, HighlightMap},
   4    markdown::ParsedMarkdown,
   5    proto, Grammar, Language, LanguageRegistry,
   6};
   7use crate::{
   8    diagnostic_set::{DiagnosticEntry, DiagnosticGroup},
   9    language_settings::{language_settings, IndentGuideSettings, LanguageSettings},
  10    markdown::parse_markdown,
  11    outline::OutlineItem,
  12    syntax_map::{
  13        SyntaxLayer, SyntaxMap, SyntaxMapCapture, SyntaxMapCaptures, SyntaxMapMatch,
  14        SyntaxMapMatches, SyntaxSnapshot, ToTreeSitterPoint,
  15    },
  16    task_context::RunnableRange,
  17    LanguageScope, Outline, OutlineConfig, RunnableCapture, RunnableTag,
  18};
  19use anyhow::{anyhow, Context, Result};
  20use async_watch as watch;
  21pub use clock::ReplicaId;
  22use futures::channel::oneshot;
  23use gpui::{
  24    AnyElement, AppContext, EventEmitter, HighlightStyle, ModelContext, Pixels, Task, TaskLabel,
  25    WindowContext,
  26};
  27use lsp::LanguageServerId;
  28use parking_lot::Mutex;
  29use serde_json::Value;
  30use similar::{ChangeTag, TextDiff};
  31use smallvec::SmallVec;
  32use smol::future::yield_now;
  33use std::{
  34    any::Any,
  35    cell::Cell,
  36    cmp::{self, Ordering, Reverse},
  37    collections::BTreeMap,
  38    ffi::OsStr,
  39    fmt,
  40    future::Future,
  41    iter::{self, Iterator, Peekable},
  42    mem,
  43    ops::{Deref, DerefMut, Range},
  44    path::{Path, PathBuf},
  45    str,
  46    sync::{Arc, LazyLock},
  47    time::{Duration, Instant, SystemTime},
  48    vec,
  49};
  50use sum_tree::TreeMap;
  51use text::operation_queue::OperationQueue;
  52use text::*;
  53pub use text::{
  54    Anchor, Bias, Buffer as TextBuffer, BufferId, BufferSnapshot as TextBufferSnapshot, Edit,
  55    OffsetRangeExt, OffsetUtf16, Patch, Point, PointUtf16, Rope, Selection, SelectionGoal,
  56    Subscription, TextDimension, TextSummary, ToOffset, ToOffsetUtf16, ToPoint, ToPointUtf16,
  57    Transaction, TransactionId, Unclipped,
  58};
  59use theme::SyntaxTheme;
  60#[cfg(any(test, feature = "test-support"))]
  61use util::RandomCharIter;
  62use util::RangeExt;
  63
  64#[cfg(any(test, feature = "test-support"))]
  65pub use {tree_sitter_rust, tree_sitter_typescript};
  66
  67pub use lsp::DiagnosticSeverity;
  68
  69/// A label for the background task spawned by the buffer to compute
  70/// a diff against the contents of its file.
  71pub static BUFFER_DIFF_TASK: LazyLock<TaskLabel> = LazyLock::new(|| TaskLabel::new());
  72
  73/// Indicate whether a [Buffer] has permissions to edit.
  74#[derive(PartialEq, Clone, Copy, Debug)]
  75pub enum Capability {
  76    /// The buffer is a mutable replica.
  77    ReadWrite,
  78    /// The buffer is a read-only replica.
  79    ReadOnly,
  80}
  81
  82pub type BufferRow = u32;
  83
  84/// An in-memory representation of a source code file, including its text,
  85/// syntax trees, git status, and diagnostics.
  86pub struct Buffer {
  87    text: TextBuffer,
  88    diff_base: Option<Rope>,
  89    git_diff: git::diff::BufferDiff,
  90    file: Option<Arc<dyn File>>,
  91    /// The mtime of the file when this buffer was last loaded from
  92    /// or saved to disk.
  93    saved_mtime: Option<SystemTime>,
  94    /// The version vector when this buffer was last loaded from
  95    /// or saved to disk.
  96    saved_version: clock::Global,
  97    preview_version: clock::Global,
  98    transaction_depth: usize,
  99    was_dirty_before_starting_transaction: Option<bool>,
 100    reload_task: Option<Task<Result<()>>>,
 101    language: Option<Arc<Language>>,
 102    autoindent_requests: Vec<Arc<AutoindentRequest>>,
 103    pending_autoindent: Option<Task<()>>,
 104    sync_parse_timeout: Duration,
 105    syntax_map: Mutex<SyntaxMap>,
 106    parsing_in_background: bool,
 107    parse_status: (watch::Sender<ParseStatus>, watch::Receiver<ParseStatus>),
 108    non_text_state_update_count: usize,
 109    diagnostics: SmallVec<[(LanguageServerId, DiagnosticSet); 2]>,
 110    remote_selections: TreeMap<ReplicaId, SelectionSet>,
 111    diagnostics_timestamp: clock::Lamport,
 112    completion_triggers: Vec<String>,
 113    completion_triggers_timestamp: clock::Lamport,
 114    deferred_ops: OperationQueue<Operation>,
 115    capability: Capability,
 116    has_conflict: bool,
 117    diff_base_version: usize,
 118    /// Memoize calls to has_changes_since(saved_version).
 119    /// The contents of a cell are (self.version, has_changes) at the time of a last call.
 120    has_unsaved_edits: Cell<(clock::Global, bool)>,
 121}
 122
 123#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 124pub enum ParseStatus {
 125    Idle,
 126    Parsing,
 127}
 128
 129/// An immutable, cheaply cloneable representation of a fixed
 130/// state of a buffer.
 131pub struct BufferSnapshot {
 132    text: text::BufferSnapshot,
 133    git_diff: git::diff::BufferDiff,
 134    pub(crate) syntax: SyntaxSnapshot,
 135    file: Option<Arc<dyn File>>,
 136    diagnostics: SmallVec<[(LanguageServerId, DiagnosticSet); 2]>,
 137    remote_selections: TreeMap<ReplicaId, SelectionSet>,
 138    language: Option<Arc<Language>>,
 139    non_text_state_update_count: usize,
 140}
 141
 142/// The kind and amount of indentation in a particular line. For now,
 143/// assumes that indentation is all the same character.
 144#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
 145pub struct IndentSize {
 146    /// The number of bytes that comprise the indentation.
 147    pub len: u32,
 148    /// The kind of whitespace used for indentation.
 149    pub kind: IndentKind,
 150}
 151
 152/// A whitespace character that's used for indentation.
 153#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
 154pub enum IndentKind {
 155    /// An ASCII space character.
 156    #[default]
 157    Space,
 158    /// An ASCII tab character.
 159    Tab,
 160}
 161
 162/// The shape of a selection cursor.
 163#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
 164pub enum CursorShape {
 165    /// A vertical bar
 166    #[default]
 167    Bar,
 168    /// A block that surrounds the following character
 169    Block,
 170    /// An underline that runs along the following character
 171    Underscore,
 172    /// A box drawn around the following character
 173    Hollow,
 174}
 175
 176#[derive(Clone, Debug)]
 177struct SelectionSet {
 178    line_mode: bool,
 179    cursor_shape: CursorShape,
 180    selections: Arc<[Selection<Anchor>]>,
 181    lamport_timestamp: clock::Lamport,
 182}
 183
 184/// A diagnostic associated with a certain range of a buffer.
 185#[derive(Clone, Debug, PartialEq, Eq)]
 186pub struct Diagnostic {
 187    /// The name of the service that produced this diagnostic.
 188    pub source: Option<String>,
 189    /// A machine-readable code that identifies this diagnostic.
 190    pub code: Option<String>,
 191    /// Whether this diagnostic is a hint, warning, or error.
 192    pub severity: DiagnosticSeverity,
 193    /// The human-readable message associated with this diagnostic.
 194    pub message: String,
 195    /// An id that identifies the group to which this diagnostic belongs.
 196    ///
 197    /// When a language server produces a diagnostic with
 198    /// one or more associated diagnostics, those diagnostics are all
 199    /// assigned a single group id.
 200    pub group_id: usize,
 201    /// Whether this diagnostic is the primary diagnostic for its group.
 202    ///
 203    /// In a given group, the primary diagnostic is the top-level diagnostic
 204    /// returned by the language server. The non-primary diagnostics are the
 205    /// associated diagnostics.
 206    pub is_primary: bool,
 207    /// Whether this diagnostic is considered to originate from an analysis of
 208    /// files on disk, as opposed to any unsaved buffer contents. This is a
 209    /// property of a given diagnostic source, and is configured for a given
 210    /// language server via the [`LspAdapter::disk_based_diagnostic_sources`](crate::LspAdapter::disk_based_diagnostic_sources) method
 211    /// for the language server.
 212    pub is_disk_based: bool,
 213    /// Whether this diagnostic marks unnecessary code.
 214    pub is_unnecessary: bool,
 215    /// Data from language server that produced this diagnostic. Passed back to the LS when we request code actions for this diagnostic.
 216    pub data: Option<Value>,
 217}
 218
 219/// TODO - move this into the `project` crate and make it private.
 220pub async fn prepare_completion_documentation(
 221    documentation: &lsp::Documentation,
 222    language_registry: &Arc<LanguageRegistry>,
 223    language: Option<Arc<Language>>,
 224) -> Documentation {
 225    match documentation {
 226        lsp::Documentation::String(text) => {
 227            if text.lines().count() <= 1 {
 228                Documentation::SingleLine(text.clone())
 229            } else {
 230                Documentation::MultiLinePlainText(text.clone())
 231            }
 232        }
 233
 234        lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
 235            lsp::MarkupKind::PlainText => {
 236                if value.lines().count() <= 1 {
 237                    Documentation::SingleLine(value.clone())
 238                } else {
 239                    Documentation::MultiLinePlainText(value.clone())
 240                }
 241            }
 242
 243            lsp::MarkupKind::Markdown => {
 244                let parsed = parse_markdown(value, language_registry, language).await;
 245                Documentation::MultiLineMarkdown(parsed)
 246            }
 247        },
 248    }
 249}
 250
 251/// Documentation associated with a [`Completion`].
 252#[derive(Clone, Debug)]
 253pub enum Documentation {
 254    /// There is no documentation for this completion.
 255    Undocumented,
 256    /// A single line of documentation.
 257    SingleLine(String),
 258    /// Multiple lines of plain text documentation.
 259    MultiLinePlainText(String),
 260    /// Markdown documentation.
 261    MultiLineMarkdown(ParsedMarkdown),
 262}
 263
 264/// An operation used to synchronize this buffer with its other replicas.
 265#[derive(Clone, Debug, PartialEq)]
 266pub enum Operation {
 267    /// A text operation.
 268    Buffer(text::Operation),
 269
 270    /// An update to the buffer's diagnostics.
 271    UpdateDiagnostics {
 272        /// The id of the language server that produced the new diagnostics.
 273        server_id: LanguageServerId,
 274        /// The diagnostics.
 275        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
 276        /// The buffer's lamport timestamp.
 277        lamport_timestamp: clock::Lamport,
 278    },
 279
 280    /// An update to the most recent selections in this buffer.
 281    UpdateSelections {
 282        /// The selections.
 283        selections: Arc<[Selection<Anchor>]>,
 284        /// The buffer's lamport timestamp.
 285        lamport_timestamp: clock::Lamport,
 286        /// Whether the selections are in 'line mode'.
 287        line_mode: bool,
 288        /// The [`CursorShape`] associated with these selections.
 289        cursor_shape: CursorShape,
 290    },
 291
 292    /// An update to the characters that should trigger autocompletion
 293    /// for this buffer.
 294    UpdateCompletionTriggers {
 295        /// The characters that trigger autocompletion.
 296        triggers: Vec<String>,
 297        /// The buffer's lamport timestamp.
 298        lamport_timestamp: clock::Lamport,
 299    },
 300}
 301
 302/// An event that occurs in a buffer.
 303#[derive(Clone, Debug, PartialEq)]
 304pub enum Event {
 305    /// The buffer was changed in a way that must be
 306    /// propagated to its other replicas.
 307    Operation(Operation),
 308    /// The buffer was edited.
 309    Edited,
 310    /// The buffer's `dirty` bit changed.
 311    DirtyChanged,
 312    /// The buffer was saved.
 313    Saved,
 314    /// The buffer's file was changed on disk.
 315    FileHandleChanged,
 316    /// The buffer was reloaded.
 317    Reloaded,
 318    /// The buffer's diff_base changed.
 319    DiffBaseChanged,
 320    /// Buffer's excerpts for a certain diff base were recalculated.
 321    DiffUpdated,
 322    /// The buffer's language was changed.
 323    LanguageChanged,
 324    /// The buffer's syntax trees were updated.
 325    Reparsed,
 326    /// The buffer's diagnostics were updated.
 327    DiagnosticsUpdated,
 328    /// The buffer gained or lost editing capabilities.
 329    CapabilityChanged,
 330    /// The buffer was explicitly requested to close.
 331    Closed,
 332    /// The buffer was discarded when closing.
 333    Discarded,
 334}
 335
 336/// The file associated with a buffer.
 337pub trait File: Send + Sync {
 338    /// Returns the [`LocalFile`] associated with this file, if the
 339    /// file is local.
 340    fn as_local(&self) -> Option<&dyn LocalFile>;
 341
 342    /// Returns whether this file is local.
 343    fn is_local(&self) -> bool {
 344        self.as_local().is_some()
 345    }
 346
 347    /// Returns the file's mtime.
 348    fn mtime(&self) -> Option<SystemTime>;
 349
 350    /// Returns the path of this file relative to the worktree's root directory.
 351    fn path(&self) -> &Arc<Path>;
 352
 353    /// Returns the path of this file relative to the worktree's parent directory (this means it
 354    /// includes the name of the worktree's root folder).
 355    fn full_path(&self, cx: &AppContext) -> PathBuf;
 356
 357    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 358    /// of its worktree, then this method will return the name of the worktree itself.
 359    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr;
 360
 361    /// Returns the id of the worktree to which this file belongs.
 362    ///
 363    /// This is needed for looking up project-specific settings.
 364    fn worktree_id(&self) -> usize;
 365
 366    /// Returns whether the file has been deleted.
 367    fn is_deleted(&self) -> bool;
 368
 369    /// Returns whether the file existed on disk at one point
 370    fn is_created(&self) -> bool {
 371        self.mtime().is_some()
 372    }
 373
 374    /// Converts this file into an [`Any`] trait object.
 375    fn as_any(&self) -> &dyn Any;
 376
 377    /// Converts this file into a protobuf message.
 378    fn to_proto(&self, cx: &AppContext) -> rpc::proto::File;
 379
 380    /// Return whether Zed considers this to be a private file.
 381    fn is_private(&self) -> bool;
 382}
 383
 384/// The file associated with a buffer, in the case where the file is on the local disk.
 385pub trait LocalFile: File {
 386    /// Returns the absolute path of this file
 387    fn abs_path(&self, cx: &AppContext) -> PathBuf;
 388
 389    /// Loads the file's contents from disk.
 390    fn load(&self, cx: &AppContext) -> Task<Result<String>>;
 391
 392    /// Returns true if the file should not be shared with collaborators.
 393    fn is_private(&self, _: &AppContext) -> bool {
 394        false
 395    }
 396}
 397
 398/// The auto-indent behavior associated with an editing operation.
 399/// For some editing operations, each affected line of text has its
 400/// indentation recomputed. For other operations, the entire block
 401/// of edited text is adjusted uniformly.
 402#[derive(Clone, Debug)]
 403pub enum AutoindentMode {
 404    /// Indent each line of inserted text.
 405    EachLine,
 406    /// Apply the same indentation adjustment to all of the lines
 407    /// in a given insertion.
 408    Block {
 409        /// The original indentation level of the first line of each
 410        /// insertion, if it has been copied.
 411        original_indent_columns: Vec<u32>,
 412    },
 413}
 414
 415#[derive(Clone)]
 416struct AutoindentRequest {
 417    before_edit: BufferSnapshot,
 418    entries: Vec<AutoindentRequestEntry>,
 419    is_block_mode: bool,
 420}
 421
 422#[derive(Clone)]
 423struct AutoindentRequestEntry {
 424    /// A range of the buffer whose indentation should be adjusted.
 425    range: Range<Anchor>,
 426    /// Whether or not these lines should be considered brand new, for the
 427    /// purpose of auto-indent. When text is not new, its indentation will
 428    /// only be adjusted if the suggested indentation level has *changed*
 429    /// since the edit was made.
 430    first_line_is_new: bool,
 431    indent_size: IndentSize,
 432    original_indent_column: Option<u32>,
 433}
 434
 435#[derive(Debug)]
 436struct IndentSuggestion {
 437    basis_row: u32,
 438    delta: Ordering,
 439    within_error: bool,
 440}
 441
 442struct BufferChunkHighlights<'a> {
 443    captures: SyntaxMapCaptures<'a>,
 444    next_capture: Option<SyntaxMapCapture<'a>>,
 445    stack: Vec<(usize, HighlightId)>,
 446    highlight_maps: Vec<HighlightMap>,
 447}
 448
 449/// An iterator that yields chunks of a buffer's text, along with their
 450/// syntax highlights and diagnostic status.
 451pub struct BufferChunks<'a> {
 452    buffer_snapshot: Option<&'a BufferSnapshot>,
 453    range: Range<usize>,
 454    chunks: text::Chunks<'a>,
 455    diagnostic_endpoints: Option<Peekable<vec::IntoIter<DiagnosticEndpoint>>>,
 456    error_depth: usize,
 457    warning_depth: usize,
 458    information_depth: usize,
 459    hint_depth: usize,
 460    unnecessary_depth: usize,
 461    highlights: Option<BufferChunkHighlights<'a>>,
 462}
 463
 464/// A chunk of a buffer's text, along with its syntax highlight and
 465/// diagnostic status.
 466#[derive(Clone, Debug, Default)]
 467pub struct Chunk<'a> {
 468    /// The text of the chunk.
 469    pub text: &'a str,
 470    /// The syntax highlighting style of the chunk.
 471    pub syntax_highlight_id: Option<HighlightId>,
 472    /// The highlight style that has been applied to this chunk in
 473    /// the editor.
 474    pub highlight_style: Option<HighlightStyle>,
 475    /// The severity of diagnostic associated with this chunk, if any.
 476    pub diagnostic_severity: Option<DiagnosticSeverity>,
 477    /// Whether this chunk of text is marked as unnecessary.
 478    pub is_unnecessary: bool,
 479    /// Whether this chunk of text was originally a tab character.
 480    pub is_tab: bool,
 481    /// An optional recipe for how the chunk should be presented.
 482    pub renderer: Option<ChunkRenderer>,
 483}
 484
 485/// A recipe for how the chunk should be presented.
 486#[derive(Clone)]
 487pub struct ChunkRenderer {
 488    /// creates a custom element to represent this chunk.
 489    pub render: Arc<dyn Send + Sync + Fn(&mut ChunkRendererContext) -> AnyElement>,
 490    /// If true, the element is constrained to the shaped width of the text.
 491    pub constrain_width: bool,
 492}
 493
 494pub struct ChunkRendererContext<'a, 'b> {
 495    pub context: &'a mut WindowContext<'b>,
 496    pub max_width: Pixels,
 497}
 498
 499impl fmt::Debug for ChunkRenderer {
 500    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 501        f.debug_struct("ChunkRenderer")
 502            .field("constrain_width", &self.constrain_width)
 503            .finish()
 504    }
 505}
 506
 507impl<'a, 'b> Deref for ChunkRendererContext<'a, 'b> {
 508    type Target = WindowContext<'b>;
 509
 510    fn deref(&self) -> &Self::Target {
 511        self.context
 512    }
 513}
 514
 515impl<'a, 'b> DerefMut for ChunkRendererContext<'a, 'b> {
 516    fn deref_mut(&mut self) -> &mut Self::Target {
 517        self.context
 518    }
 519}
 520
 521/// A set of edits to a given version of a buffer, computed asynchronously.
 522#[derive(Debug)]
 523pub struct Diff {
 524    pub(crate) base_version: clock::Global,
 525    line_ending: LineEnding,
 526    edits: Vec<(Range<usize>, Arc<str>)>,
 527}
 528
 529#[derive(Clone, Copy)]
 530pub(crate) struct DiagnosticEndpoint {
 531    offset: usize,
 532    is_start: bool,
 533    severity: DiagnosticSeverity,
 534    is_unnecessary: bool,
 535}
 536
 537/// A class of characters, used for characterizing a run of text.
 538#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug)]
 539pub enum CharKind {
 540    /// Whitespace.
 541    Whitespace,
 542    /// Punctuation.
 543    Punctuation,
 544    /// Word.
 545    Word,
 546}
 547
 548/// A runnable is a set of data about a region that could be resolved into a task
 549pub struct Runnable {
 550    pub tags: SmallVec<[RunnableTag; 1]>,
 551    pub language: Arc<Language>,
 552    pub buffer: BufferId,
 553}
 554
 555#[derive(Clone, Debug, PartialEq)]
 556pub struct IndentGuide {
 557    pub buffer_id: BufferId,
 558    pub start_row: BufferRow,
 559    pub end_row: BufferRow,
 560    pub depth: u32,
 561    pub tab_size: u32,
 562    pub settings: IndentGuideSettings,
 563}
 564
 565impl IndentGuide {
 566    pub fn indent_level(&self) -> u32 {
 567        self.depth * self.tab_size
 568    }
 569}
 570
 571impl Buffer {
 572    /// Create a new buffer with the given base text.
 573    pub fn local<T: Into<String>>(base_text: T, cx: &mut ModelContext<Self>) -> Self {
 574        Self::build(
 575            TextBuffer::new(0, cx.entity_id().as_non_zero_u64().into(), base_text.into()),
 576            None,
 577            None,
 578            Capability::ReadWrite,
 579        )
 580    }
 581
 582    /// Create a new buffer with the given base text that has proper line endings and other normalization applied.
 583    pub fn local_normalized(
 584        base_text_normalized: Rope,
 585        line_ending: LineEnding,
 586        cx: &mut ModelContext<Self>,
 587    ) -> Self {
 588        Self::build(
 589            TextBuffer::new_normalized(
 590                0,
 591                cx.entity_id().as_non_zero_u64().into(),
 592                line_ending,
 593                base_text_normalized,
 594            ),
 595            None,
 596            None,
 597            Capability::ReadWrite,
 598        )
 599    }
 600
 601    /// Create a new buffer that is a replica of a remote buffer.
 602    pub fn remote(
 603        remote_id: BufferId,
 604        replica_id: ReplicaId,
 605        capability: Capability,
 606        base_text: impl Into<String>,
 607    ) -> Self {
 608        Self::build(
 609            TextBuffer::new(replica_id, remote_id, base_text.into()),
 610            None,
 611            None,
 612            capability,
 613        )
 614    }
 615
 616    /// Create a new buffer that is a replica of a remote buffer, populating its
 617    /// state from the given protobuf message.
 618    pub fn from_proto(
 619        replica_id: ReplicaId,
 620        capability: Capability,
 621        message: proto::BufferState,
 622        file: Option<Arc<dyn File>>,
 623    ) -> Result<Self> {
 624        let buffer_id = BufferId::new(message.id)
 625            .with_context(|| anyhow!("Could not deserialize buffer_id"))?;
 626        let buffer = TextBuffer::new(replica_id, buffer_id, message.base_text);
 627        let mut this = Self::build(buffer, message.diff_base, file, capability);
 628        this.text.set_line_ending(proto::deserialize_line_ending(
 629            rpc::proto::LineEnding::from_i32(message.line_ending)
 630                .ok_or_else(|| anyhow!("missing line_ending"))?,
 631        ));
 632        this.saved_version = proto::deserialize_version(&message.saved_version);
 633        this.saved_mtime = message.saved_mtime.map(|time| time.into());
 634        Ok(this)
 635    }
 636
 637    /// Serialize the buffer's state to a protobuf message.
 638    pub fn to_proto(&self, cx: &AppContext) -> proto::BufferState {
 639        proto::BufferState {
 640            id: self.remote_id().into(),
 641            file: self.file.as_ref().map(|f| f.to_proto(cx)),
 642            base_text: self.base_text().to_string(),
 643            diff_base: self.diff_base.as_ref().map(|h| h.to_string()),
 644            line_ending: proto::serialize_line_ending(self.line_ending()) as i32,
 645            saved_version: proto::serialize_version(&self.saved_version),
 646            saved_mtime: self.saved_mtime.map(|time| time.into()),
 647        }
 648    }
 649
 650    /// Serialize as protobufs all of the changes to the buffer since the given version.
 651    pub fn serialize_ops(
 652        &self,
 653        since: Option<clock::Global>,
 654        cx: &AppContext,
 655    ) -> Task<Vec<proto::Operation>> {
 656        let mut operations = Vec::new();
 657        operations.extend(self.deferred_ops.iter().map(proto::serialize_operation));
 658
 659        operations.extend(self.remote_selections.iter().map(|(_, set)| {
 660            proto::serialize_operation(&Operation::UpdateSelections {
 661                selections: set.selections.clone(),
 662                lamport_timestamp: set.lamport_timestamp,
 663                line_mode: set.line_mode,
 664                cursor_shape: set.cursor_shape,
 665            })
 666        }));
 667
 668        for (server_id, diagnostics) in &self.diagnostics {
 669            operations.push(proto::serialize_operation(&Operation::UpdateDiagnostics {
 670                lamport_timestamp: self.diagnostics_timestamp,
 671                server_id: *server_id,
 672                diagnostics: diagnostics.iter().cloned().collect(),
 673            }));
 674        }
 675
 676        operations.push(proto::serialize_operation(
 677            &Operation::UpdateCompletionTriggers {
 678                triggers: self.completion_triggers.clone(),
 679                lamport_timestamp: self.completion_triggers_timestamp,
 680            },
 681        ));
 682
 683        let text_operations = self.text.operations().clone();
 684        cx.background_executor().spawn(async move {
 685            let since = since.unwrap_or_default();
 686            operations.extend(
 687                text_operations
 688                    .iter()
 689                    .filter(|(_, op)| !since.observed(op.timestamp()))
 690                    .map(|(_, op)| proto::serialize_operation(&Operation::Buffer(op.clone()))),
 691            );
 692            operations.sort_unstable_by_key(proto::lamport_timestamp_for_operation);
 693            operations
 694        })
 695    }
 696
 697    /// Assign a language to the buffer, returning the buffer.
 698    pub fn with_language(mut self, language: Arc<Language>, cx: &mut ModelContext<Self>) -> Self {
 699        self.set_language(Some(language), cx);
 700        self
 701    }
 702
 703    /// Returns the [Capability] of this buffer.
 704    pub fn capability(&self) -> Capability {
 705        self.capability
 706    }
 707
 708    /// Whether this buffer can only be read.
 709    pub fn read_only(&self) -> bool {
 710        self.capability == Capability::ReadOnly
 711    }
 712
 713    /// Builds a [Buffer] with the given underlying [TextBuffer], diff base, [File] and [Capability].
 714    pub fn build(
 715        buffer: TextBuffer,
 716        diff_base: Option<String>,
 717        file: Option<Arc<dyn File>>,
 718        capability: Capability,
 719    ) -> Self {
 720        let saved_mtime = file.as_ref().and_then(|file| file.mtime());
 721
 722        Self {
 723            saved_mtime,
 724            saved_version: buffer.version(),
 725            preview_version: buffer.version(),
 726            reload_task: None,
 727            transaction_depth: 0,
 728            was_dirty_before_starting_transaction: None,
 729            has_unsaved_edits: Cell::new((buffer.version(), false)),
 730            text: buffer,
 731            diff_base: diff_base
 732                .map(|mut raw_diff_base| {
 733                    LineEnding::normalize(&mut raw_diff_base);
 734                    raw_diff_base
 735                })
 736                .map(Rope::from),
 737            diff_base_version: 0,
 738            git_diff: git::diff::BufferDiff::new(),
 739            file,
 740            capability,
 741            syntax_map: Mutex::new(SyntaxMap::new()),
 742            parsing_in_background: false,
 743            non_text_state_update_count: 0,
 744            sync_parse_timeout: Duration::from_millis(1),
 745            parse_status: async_watch::channel(ParseStatus::Idle),
 746            autoindent_requests: Default::default(),
 747            pending_autoindent: Default::default(),
 748            language: None,
 749            remote_selections: Default::default(),
 750            diagnostics: Default::default(),
 751            diagnostics_timestamp: Default::default(),
 752            completion_triggers: Default::default(),
 753            completion_triggers_timestamp: Default::default(),
 754            deferred_ops: OperationQueue::new(),
 755            has_conflict: false,
 756        }
 757    }
 758
 759    /// Retrieve a snapshot of the buffer's current state. This is computationally
 760    /// cheap, and allows reading from the buffer on a background thread.
 761    pub fn snapshot(&self) -> BufferSnapshot {
 762        let text = self.text.snapshot();
 763        let mut syntax_map = self.syntax_map.lock();
 764        syntax_map.interpolate(&text);
 765        let syntax = syntax_map.snapshot();
 766
 767        BufferSnapshot {
 768            text,
 769            syntax,
 770            git_diff: self.git_diff.clone(),
 771            file: self.file.clone(),
 772            remote_selections: self.remote_selections.clone(),
 773            diagnostics: self.diagnostics.clone(),
 774            language: self.language.clone(),
 775            non_text_state_update_count: self.non_text_state_update_count,
 776        }
 777    }
 778
 779    #[cfg(test)]
 780    pub(crate) fn as_text_snapshot(&self) -> &text::BufferSnapshot {
 781        &self.text
 782    }
 783
 784    /// Retrieve a snapshot of the buffer's raw text, without any
 785    /// language-related state like the syntax tree or diagnostics.
 786    pub fn text_snapshot(&self) -> text::BufferSnapshot {
 787        self.text.snapshot()
 788    }
 789
 790    /// The file associated with the buffer, if any.
 791    pub fn file(&self) -> Option<&Arc<dyn File>> {
 792        self.file.as_ref()
 793    }
 794
 795    /// The version of the buffer that was last saved or reloaded from disk.
 796    pub fn saved_version(&self) -> &clock::Global {
 797        &self.saved_version
 798    }
 799
 800    /// The mtime of the buffer's file when the buffer was last saved or reloaded from disk.
 801    pub fn saved_mtime(&self) -> Option<SystemTime> {
 802        self.saved_mtime
 803    }
 804
 805    /// Assign a language to the buffer.
 806    pub fn set_language(&mut self, language: Option<Arc<Language>>, cx: &mut ModelContext<Self>) {
 807        self.non_text_state_update_count += 1;
 808        self.syntax_map.lock().clear();
 809        self.language = language;
 810        self.reparse(cx);
 811        cx.emit(Event::LanguageChanged);
 812    }
 813
 814    /// Assign a language registry to the buffer. This allows the buffer to retrieve
 815    /// other languages if parts of the buffer are written in different languages.
 816    pub fn set_language_registry(&mut self, language_registry: Arc<LanguageRegistry>) {
 817        self.syntax_map
 818            .lock()
 819            .set_language_registry(language_registry);
 820    }
 821
 822    pub fn language_registry(&self) -> Option<Arc<LanguageRegistry>> {
 823        self.syntax_map.lock().language_registry()
 824    }
 825
 826    /// Assign the buffer a new [Capability].
 827    pub fn set_capability(&mut self, capability: Capability, cx: &mut ModelContext<Self>) {
 828        self.capability = capability;
 829        cx.emit(Event::CapabilityChanged)
 830    }
 831
 832    /// This method is called to signal that the buffer has been saved.
 833    pub fn did_save(
 834        &mut self,
 835        version: clock::Global,
 836        mtime: Option<SystemTime>,
 837        cx: &mut ModelContext<Self>,
 838    ) {
 839        self.saved_version = version;
 840        self.has_unsaved_edits
 841            .set((self.saved_version().clone(), false));
 842        self.has_conflict = false;
 843        self.saved_mtime = mtime;
 844        cx.emit(Event::Saved);
 845        cx.notify();
 846    }
 847
 848    /// This method is called to signal that the buffer has been discarded.
 849    pub fn discarded(&mut self, cx: &mut ModelContext<Self>) {
 850        cx.emit(Event::Discarded);
 851        cx.notify();
 852    }
 853
 854    /// Reloads the contents of the buffer from disk.
 855    pub fn reload(
 856        &mut self,
 857        cx: &mut ModelContext<Self>,
 858    ) -> oneshot::Receiver<Option<Transaction>> {
 859        let (tx, rx) = futures::channel::oneshot::channel();
 860        let prev_version = self.text.version();
 861        self.reload_task = Some(cx.spawn(|this, mut cx| async move {
 862            let Some((new_mtime, new_text)) = this.update(&mut cx, |this, cx| {
 863                let file = this.file.as_ref()?.as_local()?;
 864                Some((file.mtime(), file.load(cx)))
 865            })?
 866            else {
 867                return Ok(());
 868            };
 869
 870            let new_text = new_text.await?;
 871            let diff = this
 872                .update(&mut cx, |this, cx| this.diff(new_text.clone(), cx))?
 873                .await;
 874            this.update(&mut cx, |this, cx| {
 875                if this.version() == diff.base_version {
 876                    this.finalize_last_transaction();
 877                    this.apply_diff(diff, cx);
 878                    tx.send(this.finalize_last_transaction().cloned()).ok();
 879                    this.has_conflict = false;
 880                    this.did_reload(this.version(), this.line_ending(), new_mtime, cx);
 881                } else {
 882                    if !diff.edits.is_empty()
 883                        || this
 884                            .edits_since::<usize>(&diff.base_version)
 885                            .next()
 886                            .is_some()
 887                    {
 888                        this.has_conflict = true;
 889                    }
 890
 891                    this.did_reload(prev_version, this.line_ending(), this.saved_mtime, cx);
 892                }
 893
 894                this.reload_task.take();
 895            })
 896        }));
 897        rx
 898    }
 899
 900    /// This method is called to signal that the buffer has been reloaded.
 901    pub fn did_reload(
 902        &mut self,
 903        version: clock::Global,
 904        line_ending: LineEnding,
 905        mtime: Option<SystemTime>,
 906        cx: &mut ModelContext<Self>,
 907    ) {
 908        self.saved_version = version;
 909        self.has_unsaved_edits
 910            .set((self.saved_version.clone(), false));
 911        self.text.set_line_ending(line_ending);
 912        self.saved_mtime = mtime;
 913        cx.emit(Event::Reloaded);
 914        cx.notify();
 915    }
 916
 917    /// Updates the [File] backing this buffer. This should be called when
 918    /// the file has changed or has been deleted.
 919    pub fn file_updated(&mut self, new_file: Arc<dyn File>, cx: &mut ModelContext<Self>) {
 920        let mut file_changed = false;
 921
 922        if let Some(old_file) = self.file.as_ref() {
 923            if new_file.path() != old_file.path() {
 924                file_changed = true;
 925            }
 926
 927            if new_file.is_deleted() {
 928                if !old_file.is_deleted() {
 929                    file_changed = true;
 930                    if !self.is_dirty() {
 931                        cx.emit(Event::DirtyChanged);
 932                    }
 933                }
 934            } else {
 935                let new_mtime = new_file.mtime();
 936                if new_mtime != old_file.mtime() {
 937                    file_changed = true;
 938
 939                    if !self.is_dirty() {
 940                        self.reload(cx).close();
 941                    }
 942                }
 943            }
 944        } else {
 945            file_changed = true;
 946        };
 947
 948        self.file = Some(new_file);
 949        if file_changed {
 950            self.non_text_state_update_count += 1;
 951            cx.emit(Event::FileHandleChanged);
 952            cx.notify();
 953        }
 954    }
 955
 956    /// Returns the current diff base, see [Buffer::set_diff_base].
 957    pub fn diff_base(&self) -> Option<&Rope> {
 958        self.diff_base.as_ref()
 959    }
 960
 961    /// Sets the text that will be used to compute a Git diff
 962    /// against the buffer text.
 963    pub fn set_diff_base(&mut self, diff_base: Option<String>, cx: &mut ModelContext<Self>) {
 964        self.diff_base = diff_base
 965            .map(|mut raw_diff_base| {
 966                LineEnding::normalize(&mut raw_diff_base);
 967                raw_diff_base
 968            })
 969            .map(Rope::from);
 970        self.diff_base_version += 1;
 971        if let Some(recalc_task) = self.git_diff_recalc(cx) {
 972            cx.spawn(|buffer, mut cx| async move {
 973                recalc_task.await;
 974                buffer
 975                    .update(&mut cx, |_, cx| {
 976                        cx.emit(Event::DiffBaseChanged);
 977                    })
 978                    .ok();
 979            })
 980            .detach();
 981        }
 982    }
 983
 984    /// Returns a number, unique per diff base set to the buffer.
 985    pub fn diff_base_version(&self) -> usize {
 986        self.diff_base_version
 987    }
 988
 989    /// Recomputes the Git diff status.
 990    pub fn git_diff_recalc(&mut self, cx: &mut ModelContext<Self>) -> Option<Task<()>> {
 991        let diff_base = self.diff_base.clone()?;
 992        let snapshot = self.snapshot();
 993
 994        let mut diff = self.git_diff.clone();
 995        let diff = cx.background_executor().spawn(async move {
 996            diff.update(&diff_base, &snapshot).await;
 997            diff
 998        });
 999
1000        Some(cx.spawn(|this, mut cx| async move {
1001            let buffer_diff = diff.await;
1002            this.update(&mut cx, |this, cx| {
1003                this.git_diff = buffer_diff;
1004                this.non_text_state_update_count += 1;
1005                cx.emit(Event::DiffUpdated);
1006            })
1007            .ok();
1008        }))
1009    }
1010
1011    /// Returns the primary [Language] assigned to this [Buffer].
1012    pub fn language(&self) -> Option<&Arc<Language>> {
1013        self.language.as_ref()
1014    }
1015
1016    /// Returns the [Language] at the given location.
1017    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<Arc<Language>> {
1018        let offset = position.to_offset(self);
1019        self.syntax_map
1020            .lock()
1021            .layers_for_range(offset..offset, &self.text, false)
1022            .last()
1023            .map(|info| info.language.clone())
1024            .or_else(|| self.language.clone())
1025    }
1026
1027    /// An integer version number that accounts for all updates besides
1028    /// the buffer's text itself (which is versioned via a version vector).
1029    pub fn non_text_state_update_count(&self) -> usize {
1030        self.non_text_state_update_count
1031    }
1032
1033    /// Whether the buffer is being parsed in the background.
1034    #[cfg(any(test, feature = "test-support"))]
1035    pub fn is_parsing(&self) -> bool {
1036        self.parsing_in_background
1037    }
1038
1039    /// Indicates whether the buffer contains any regions that may be
1040    /// written in a language that hasn't been loaded yet.
1041    pub fn contains_unknown_injections(&self) -> bool {
1042        self.syntax_map.lock().contains_unknown_injections()
1043    }
1044
1045    #[cfg(test)]
1046    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
1047        self.sync_parse_timeout = timeout;
1048    }
1049
1050    /// Called after an edit to synchronize the buffer's main parse tree with
1051    /// the buffer's new underlying state.
1052    ///
1053    /// Locks the syntax map and interpolates the edits since the last reparse
1054    /// into the foreground syntax tree.
1055    ///
1056    /// Then takes a stable snapshot of the syntax map before unlocking it.
1057    /// The snapshot with the interpolated edits is sent to a background thread,
1058    /// where we ask Tree-sitter to perform an incremental parse.
1059    ///
1060    /// Meanwhile, in the foreground, we block the main thread for up to 1ms
1061    /// waiting on the parse to complete. As soon as it completes, we proceed
1062    /// synchronously, unless a 1ms timeout elapses.
1063    ///
1064    /// If we time out waiting on the parse, we spawn a second task waiting
1065    /// until the parse does complete and return with the interpolated tree still
1066    /// in the foreground. When the background parse completes, call back into
1067    /// the main thread and assign the foreground parse state.
1068    ///
1069    /// If the buffer or grammar changed since the start of the background parse,
1070    /// initiate an additional reparse recursively. To avoid concurrent parses
1071    /// for the same buffer, we only initiate a new parse if we are not already
1072    /// parsing in the background.
1073    pub fn reparse(&mut self, cx: &mut ModelContext<Self>) {
1074        if self.parsing_in_background {
1075            return;
1076        }
1077        let language = if let Some(language) = self.language.clone() {
1078            language
1079        } else {
1080            return;
1081        };
1082
1083        let text = self.text_snapshot();
1084        let parsed_version = self.version();
1085
1086        let mut syntax_map = self.syntax_map.lock();
1087        syntax_map.interpolate(&text);
1088        let language_registry = syntax_map.language_registry();
1089        let mut syntax_snapshot = syntax_map.snapshot();
1090        drop(syntax_map);
1091
1092        let parse_task = cx.background_executor().spawn({
1093            let language = language.clone();
1094            let language_registry = language_registry.clone();
1095            async move {
1096                syntax_snapshot.reparse(&text, language_registry, language);
1097                syntax_snapshot
1098            }
1099        });
1100
1101        self.parse_status.0.send(ParseStatus::Parsing).unwrap();
1102        match cx
1103            .background_executor()
1104            .block_with_timeout(self.sync_parse_timeout, parse_task)
1105        {
1106            Ok(new_syntax_snapshot) => {
1107                self.did_finish_parsing(new_syntax_snapshot, cx);
1108                return;
1109            }
1110            Err(parse_task) => {
1111                self.parsing_in_background = true;
1112                cx.spawn(move |this, mut cx| async move {
1113                    let new_syntax_map = parse_task.await;
1114                    this.update(&mut cx, move |this, cx| {
1115                        let grammar_changed =
1116                            this.language.as_ref().map_or(true, |current_language| {
1117                                !Arc::ptr_eq(&language, current_language)
1118                            });
1119                        let language_registry_changed = new_syntax_map
1120                            .contains_unknown_injections()
1121                            && language_registry.map_or(false, |registry| {
1122                                registry.version() != new_syntax_map.language_registry_version()
1123                            });
1124                        let parse_again = language_registry_changed
1125                            || grammar_changed
1126                            || this.version.changed_since(&parsed_version);
1127                        this.did_finish_parsing(new_syntax_map, cx);
1128                        this.parsing_in_background = false;
1129                        if parse_again {
1130                            this.reparse(cx);
1131                        }
1132                    })
1133                    .ok();
1134                })
1135                .detach();
1136            }
1137        }
1138    }
1139
1140    fn did_finish_parsing(&mut self, syntax_snapshot: SyntaxSnapshot, cx: &mut ModelContext<Self>) {
1141        self.non_text_state_update_count += 1;
1142        self.syntax_map.lock().did_parse(syntax_snapshot);
1143        self.request_autoindent(cx);
1144        self.parse_status.0.send(ParseStatus::Idle).unwrap();
1145        cx.emit(Event::Reparsed);
1146        cx.notify();
1147    }
1148
1149    pub fn parse_status(&self) -> watch::Receiver<ParseStatus> {
1150        self.parse_status.1.clone()
1151    }
1152
1153    /// Assign to the buffer a set of diagnostics created by a given language server.
1154    pub fn update_diagnostics(
1155        &mut self,
1156        server_id: LanguageServerId,
1157        diagnostics: DiagnosticSet,
1158        cx: &mut ModelContext<Self>,
1159    ) {
1160        let lamport_timestamp = self.text.lamport_clock.tick();
1161        let op = Operation::UpdateDiagnostics {
1162            server_id,
1163            diagnostics: diagnostics.iter().cloned().collect(),
1164            lamport_timestamp,
1165        };
1166        self.apply_diagnostic_update(server_id, diagnostics, lamport_timestamp, cx);
1167        self.send_operation(op, cx);
1168    }
1169
1170    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
1171        if let Some(indent_sizes) = self.compute_autoindents() {
1172            let indent_sizes = cx.background_executor().spawn(indent_sizes);
1173            match cx
1174                .background_executor()
1175                .block_with_timeout(Duration::from_micros(500), indent_sizes)
1176            {
1177                Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
1178                Err(indent_sizes) => {
1179                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
1180                        let indent_sizes = indent_sizes.await;
1181                        this.update(&mut cx, |this, cx| {
1182                            this.apply_autoindents(indent_sizes, cx);
1183                        })
1184                        .ok();
1185                    }));
1186                }
1187            }
1188        } else {
1189            self.autoindent_requests.clear();
1190        }
1191    }
1192
1193    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>>> {
1194        let max_rows_between_yields = 100;
1195        let snapshot = self.snapshot();
1196        if snapshot.syntax.is_empty() || self.autoindent_requests.is_empty() {
1197            return None;
1198        }
1199
1200        let autoindent_requests = self.autoindent_requests.clone();
1201        Some(async move {
1202            let mut indent_sizes = BTreeMap::new();
1203            for request in autoindent_requests {
1204                // Resolve each edited range to its row in the current buffer and in the
1205                // buffer before this batch of edits.
1206                let mut row_ranges = Vec::new();
1207                let mut old_to_new_rows = BTreeMap::new();
1208                let mut language_indent_sizes_by_new_row = Vec::new();
1209                for entry in &request.entries {
1210                    let position = entry.range.start;
1211                    let new_row = position.to_point(&snapshot).row;
1212                    let new_end_row = entry.range.end.to_point(&snapshot).row + 1;
1213                    language_indent_sizes_by_new_row.push((new_row, entry.indent_size));
1214
1215                    if !entry.first_line_is_new {
1216                        let old_row = position.to_point(&request.before_edit).row;
1217                        old_to_new_rows.insert(old_row, new_row);
1218                    }
1219                    row_ranges.push((new_row..new_end_row, entry.original_indent_column));
1220                }
1221
1222                // Build a map containing the suggested indentation for each of the edited lines
1223                // with respect to the state of the buffer before these edits. This map is keyed
1224                // by the rows for these lines in the current state of the buffer.
1225                let mut old_suggestions = BTreeMap::<u32, (IndentSize, bool)>::default();
1226                let old_edited_ranges =
1227                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
1228                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1229                let mut language_indent_size = IndentSize::default();
1230                for old_edited_range in old_edited_ranges {
1231                    let suggestions = request
1232                        .before_edit
1233                        .suggest_autoindents(old_edited_range.clone())
1234                        .into_iter()
1235                        .flatten();
1236                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
1237                        if let Some(suggestion) = suggestion {
1238                            let new_row = *old_to_new_rows.get(&old_row).unwrap();
1239
1240                            // Find the indent size based on the language for this row.
1241                            while let Some((row, size)) = language_indent_sizes.peek() {
1242                                if *row > new_row {
1243                                    break;
1244                                }
1245                                language_indent_size = *size;
1246                                language_indent_sizes.next();
1247                            }
1248
1249                            let suggested_indent = old_to_new_rows
1250                                .get(&suggestion.basis_row)
1251                                .and_then(|from_row| {
1252                                    Some(old_suggestions.get(from_row).copied()?.0)
1253                                })
1254                                .unwrap_or_else(|| {
1255                                    request
1256                                        .before_edit
1257                                        .indent_size_for_line(suggestion.basis_row)
1258                                })
1259                                .with_delta(suggestion.delta, language_indent_size);
1260                            old_suggestions
1261                                .insert(new_row, (suggested_indent, suggestion.within_error));
1262                        }
1263                    }
1264                    yield_now().await;
1265                }
1266
1267                // In block mode, only compute indentation suggestions for the first line
1268                // of each insertion. Otherwise, compute suggestions for every inserted line.
1269                let new_edited_row_ranges = contiguous_ranges(
1270                    row_ranges.iter().flat_map(|(range, _)| {
1271                        if request.is_block_mode {
1272                            range.start..range.start + 1
1273                        } else {
1274                            range.clone()
1275                        }
1276                    }),
1277                    max_rows_between_yields,
1278                );
1279
1280                // Compute new suggestions for each line, but only include them in the result
1281                // if they differ from the old suggestion for that line.
1282                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1283                let mut language_indent_size = IndentSize::default();
1284                for new_edited_row_range in new_edited_row_ranges {
1285                    let suggestions = snapshot
1286                        .suggest_autoindents(new_edited_row_range.clone())
1287                        .into_iter()
1288                        .flatten();
1289                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
1290                        if let Some(suggestion) = suggestion {
1291                            // Find the indent size based on the language for this row.
1292                            while let Some((row, size)) = language_indent_sizes.peek() {
1293                                if *row > new_row {
1294                                    break;
1295                                }
1296                                language_indent_size = *size;
1297                                language_indent_sizes.next();
1298                            }
1299
1300                            let suggested_indent = indent_sizes
1301                                .get(&suggestion.basis_row)
1302                                .copied()
1303                                .unwrap_or_else(|| {
1304                                    snapshot.indent_size_for_line(suggestion.basis_row)
1305                                })
1306                                .with_delta(suggestion.delta, language_indent_size);
1307                            if old_suggestions.get(&new_row).map_or(
1308                                true,
1309                                |(old_indentation, was_within_error)| {
1310                                    suggested_indent != *old_indentation
1311                                        && (!suggestion.within_error || *was_within_error)
1312                                },
1313                            ) {
1314                                indent_sizes.insert(new_row, suggested_indent);
1315                            }
1316                        }
1317                    }
1318                    yield_now().await;
1319                }
1320
1321                // For each block of inserted text, adjust the indentation of the remaining
1322                // lines of the block by the same amount as the first line was adjusted.
1323                if request.is_block_mode {
1324                    for (row_range, original_indent_column) in
1325                        row_ranges
1326                            .into_iter()
1327                            .filter_map(|(range, original_indent_column)| {
1328                                if range.len() > 1 {
1329                                    Some((range, original_indent_column?))
1330                                } else {
1331                                    None
1332                                }
1333                            })
1334                    {
1335                        let new_indent = indent_sizes
1336                            .get(&row_range.start)
1337                            .copied()
1338                            .unwrap_or_else(|| snapshot.indent_size_for_line(row_range.start));
1339                        let delta = new_indent.len as i64 - original_indent_column as i64;
1340                        if delta != 0 {
1341                            for row in row_range.skip(1) {
1342                                indent_sizes.entry(row).or_insert_with(|| {
1343                                    let mut size = snapshot.indent_size_for_line(row);
1344                                    if size.kind == new_indent.kind {
1345                                        match delta.cmp(&0) {
1346                                            Ordering::Greater => size.len += delta as u32,
1347                                            Ordering::Less => {
1348                                                size.len = size.len.saturating_sub(-delta as u32)
1349                                            }
1350                                            Ordering::Equal => {}
1351                                        }
1352                                    }
1353                                    size
1354                                });
1355                            }
1356                        }
1357                    }
1358                }
1359            }
1360
1361            indent_sizes
1362        })
1363    }
1364
1365    fn apply_autoindents(
1366        &mut self,
1367        indent_sizes: BTreeMap<u32, IndentSize>,
1368        cx: &mut ModelContext<Self>,
1369    ) {
1370        self.autoindent_requests.clear();
1371
1372        let edits: Vec<_> = indent_sizes
1373            .into_iter()
1374            .filter_map(|(row, indent_size)| {
1375                let current_size = indent_size_for_line(self, row);
1376                Self::edit_for_indent_size_adjustment(row, current_size, indent_size)
1377            })
1378            .collect();
1379
1380        let preserve_preview = self.preserve_preview();
1381        self.edit(edits, None, cx);
1382        if preserve_preview {
1383            self.refresh_preview();
1384        }
1385    }
1386
1387    /// Create a minimal edit that will cause the given row to be indented
1388    /// with the given size. After applying this edit, the length of the line
1389    /// will always be at least `new_size.len`.
1390    pub fn edit_for_indent_size_adjustment(
1391        row: u32,
1392        current_size: IndentSize,
1393        new_size: IndentSize,
1394    ) -> Option<(Range<Point>, String)> {
1395        if new_size.kind == current_size.kind {
1396            match new_size.len.cmp(&current_size.len) {
1397                Ordering::Greater => {
1398                    let point = Point::new(row, 0);
1399                    Some((
1400                        point..point,
1401                        iter::repeat(new_size.char())
1402                            .take((new_size.len - current_size.len) as usize)
1403                            .collect::<String>(),
1404                    ))
1405                }
1406
1407                Ordering::Less => Some((
1408                    Point::new(row, 0)..Point::new(row, current_size.len - new_size.len),
1409                    String::new(),
1410                )),
1411
1412                Ordering::Equal => None,
1413            }
1414        } else {
1415            Some((
1416                Point::new(row, 0)..Point::new(row, current_size.len),
1417                iter::repeat(new_size.char())
1418                    .take(new_size.len as usize)
1419                    .collect::<String>(),
1420            ))
1421        }
1422    }
1423
1424    /// Spawns a background task that asynchronously computes a `Diff` between the buffer's text
1425    /// and the given new text.
1426    pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
1427        let old_text = self.as_rope().clone();
1428        let base_version = self.version();
1429        cx.background_executor()
1430            .spawn_labeled(*BUFFER_DIFF_TASK, async move {
1431                let old_text = old_text.to_string();
1432                let line_ending = LineEnding::detect(&new_text);
1433                LineEnding::normalize(&mut new_text);
1434
1435                let diff = TextDiff::from_chars(old_text.as_str(), new_text.as_str());
1436                let empty: Arc<str> = Arc::default();
1437
1438                let mut edits = Vec::new();
1439                let mut old_offset = 0;
1440                let mut new_offset = 0;
1441                let mut last_edit: Option<(Range<usize>, Range<usize>)> = None;
1442                for change in diff.iter_all_changes().map(Some).chain([None]) {
1443                    if let Some(change) = &change {
1444                        let len = change.value().len();
1445                        match change.tag() {
1446                            ChangeTag::Equal => {
1447                                old_offset += len;
1448                                new_offset += len;
1449                            }
1450                            ChangeTag::Delete => {
1451                                let old_end_offset = old_offset + len;
1452                                if let Some((last_old_range, _)) = &mut last_edit {
1453                                    last_old_range.end = old_end_offset;
1454                                } else {
1455                                    last_edit =
1456                                        Some((old_offset..old_end_offset, new_offset..new_offset));
1457                                }
1458                                old_offset = old_end_offset;
1459                            }
1460                            ChangeTag::Insert => {
1461                                let new_end_offset = new_offset + len;
1462                                if let Some((_, last_new_range)) = &mut last_edit {
1463                                    last_new_range.end = new_end_offset;
1464                                } else {
1465                                    last_edit =
1466                                        Some((old_offset..old_offset, new_offset..new_end_offset));
1467                                }
1468                                new_offset = new_end_offset;
1469                            }
1470                        }
1471                    }
1472
1473                    if let Some((old_range, new_range)) = &last_edit {
1474                        if old_offset > old_range.end
1475                            || new_offset > new_range.end
1476                            || change.is_none()
1477                        {
1478                            let text = if new_range.is_empty() {
1479                                empty.clone()
1480                            } else {
1481                                new_text[new_range.clone()].into()
1482                            };
1483                            edits.push((old_range.clone(), text));
1484                            last_edit.take();
1485                        }
1486                    }
1487                }
1488
1489                Diff {
1490                    base_version,
1491                    line_ending,
1492                    edits,
1493                }
1494            })
1495    }
1496
1497    /// Spawns a background task that searches the buffer for any whitespace
1498    /// at the ends of a lines, and returns a `Diff` that removes that whitespace.
1499    pub fn remove_trailing_whitespace(&self, cx: &AppContext) -> Task<Diff> {
1500        let old_text = self.as_rope().clone();
1501        let line_ending = self.line_ending();
1502        let base_version = self.version();
1503        cx.background_executor().spawn(async move {
1504            let ranges = trailing_whitespace_ranges(&old_text);
1505            let empty = Arc::<str>::from("");
1506            Diff {
1507                base_version,
1508                line_ending,
1509                edits: ranges
1510                    .into_iter()
1511                    .map(|range| (range, empty.clone()))
1512                    .collect(),
1513            }
1514        })
1515    }
1516
1517    /// Ensures that the buffer ends with a single newline character, and
1518    /// no other whitespace.
1519    pub fn ensure_final_newline(&mut self, cx: &mut ModelContext<Self>) {
1520        let len = self.len();
1521        let mut offset = len;
1522        for chunk in self.as_rope().reversed_chunks_in_range(0..len) {
1523            let non_whitespace_len = chunk
1524                .trim_end_matches(|c: char| c.is_ascii_whitespace())
1525                .len();
1526            offset -= chunk.len();
1527            offset += non_whitespace_len;
1528            if non_whitespace_len != 0 {
1529                if offset == len - 1 && chunk.get(non_whitespace_len..) == Some("\n") {
1530                    return;
1531                }
1532                break;
1533            }
1534        }
1535        self.edit([(offset..len, "\n")], None, cx);
1536    }
1537
1538    /// Applies a diff to the buffer. If the buffer has changed since the given diff was
1539    /// calculated, then adjust the diff to account for those changes, and discard any
1540    /// parts of the diff that conflict with those changes.
1541    pub fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1542        // Check for any edits to the buffer that have occurred since this diff
1543        // was computed.
1544        let snapshot = self.snapshot();
1545        let mut edits_since = snapshot.edits_since::<usize>(&diff.base_version).peekable();
1546        let mut delta = 0;
1547        let adjusted_edits = diff.edits.into_iter().filter_map(|(range, new_text)| {
1548            while let Some(edit_since) = edits_since.peek() {
1549                // If the edit occurs after a diff hunk, then it does not
1550                // affect that hunk.
1551                if edit_since.old.start > range.end {
1552                    break;
1553                }
1554                // If the edit precedes the diff hunk, then adjust the hunk
1555                // to reflect the edit.
1556                else if edit_since.old.end < range.start {
1557                    delta += edit_since.new_len() as i64 - edit_since.old_len() as i64;
1558                    edits_since.next();
1559                }
1560                // If the edit intersects a diff hunk, then discard that hunk.
1561                else {
1562                    return None;
1563                }
1564            }
1565
1566            let start = (range.start as i64 + delta) as usize;
1567            let end = (range.end as i64 + delta) as usize;
1568            Some((start..end, new_text))
1569        });
1570
1571        self.start_transaction();
1572        self.text.set_line_ending(diff.line_ending);
1573        self.edit(adjusted_edits, None, cx);
1574        self.end_transaction(cx)
1575    }
1576
1577    fn has_unsaved_edits(&self) -> bool {
1578        let (last_version, has_unsaved_edits) = self.has_unsaved_edits.take();
1579
1580        if last_version == self.version {
1581            self.has_unsaved_edits
1582                .set((last_version, has_unsaved_edits));
1583            return has_unsaved_edits;
1584        }
1585
1586        let has_edits = self.has_edits_since(&self.saved_version);
1587        self.has_unsaved_edits
1588            .set((self.version.clone(), has_edits));
1589        has_edits
1590    }
1591
1592    /// Checks if the buffer has unsaved changes.
1593    pub fn is_dirty(&self) -> bool {
1594        self.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
2629            .layers_for_range(0..self.len(), &self.text, true)
2630    }
2631
2632    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
2633        let offset = position.to_offset(self);
2634        self.syntax
2635            .layers_for_range(offset..offset, &self.text, false)
2636            .filter(|l| l.node().end_byte() > offset)
2637            .last()
2638    }
2639
2640    /// Returns the main [Language]
2641    pub fn language(&self) -> Option<&Arc<Language>> {
2642        self.language.as_ref()
2643    }
2644
2645    /// Returns the [Language] at the given location.
2646    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
2647        self.syntax_layer_at(position)
2648            .map(|info| info.language)
2649            .or(self.language.as_ref())
2650    }
2651
2652    /// Returns the settings for the language at the given location.
2653    pub fn settings_at<'a, D: ToOffset>(
2654        &self,
2655        position: D,
2656        cx: &'a AppContext,
2657    ) -> &'a LanguageSettings {
2658        language_settings(self.language_at(position), self.file.as_ref(), cx)
2659    }
2660
2661    /// Returns the [LanguageScope] at the given location.
2662    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
2663        let offset = position.to_offset(self);
2664        let mut scope = None;
2665        let mut smallest_range: Option<Range<usize>> = None;
2666
2667        // Use the layer that has the smallest node intersecting the given point.
2668        for layer in self
2669            .syntax
2670            .layers_for_range(offset..offset, &self.text, false)
2671        {
2672            let mut cursor = layer.node().walk();
2673
2674            let mut range = None;
2675            loop {
2676                let child_range = cursor.node().byte_range();
2677                if !child_range.to_inclusive().contains(&offset) {
2678                    break;
2679                }
2680
2681                range = Some(child_range);
2682                if cursor.goto_first_child_for_byte(offset).is_none() {
2683                    break;
2684                }
2685            }
2686
2687            if let Some(range) = range {
2688                if smallest_range
2689                    .as_ref()
2690                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
2691                {
2692                    smallest_range = Some(range);
2693                    scope = Some(LanguageScope {
2694                        language: layer.language.clone(),
2695                        override_id: layer.override_id(offset, &self.text),
2696                    });
2697                }
2698            }
2699        }
2700
2701        scope.or_else(|| {
2702            self.language.clone().map(|language| LanguageScope {
2703                language,
2704                override_id: None,
2705            })
2706        })
2707    }
2708
2709    /// Returns a tuple of the range and character kind of the word
2710    /// surrounding the given position.
2711    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2712        let mut start = start.to_offset(self);
2713        let mut end = start;
2714        let mut next_chars = self.chars_at(start).peekable();
2715        let mut prev_chars = self.reversed_chars_at(start).peekable();
2716
2717        let scope = self.language_scope_at(start);
2718        let kind = |c| char_kind(&scope, c);
2719        let word_kind = cmp::max(
2720            prev_chars.peek().copied().map(kind),
2721            next_chars.peek().copied().map(kind),
2722        );
2723
2724        for ch in prev_chars {
2725            if Some(kind(ch)) == word_kind && ch != '\n' {
2726                start -= ch.len_utf8();
2727            } else {
2728                break;
2729            }
2730        }
2731
2732        for ch in next_chars {
2733            if Some(kind(ch)) == word_kind && ch != '\n' {
2734                end += ch.len_utf8();
2735            } else {
2736                break;
2737            }
2738        }
2739
2740        (start..end, word_kind)
2741    }
2742
2743    /// Returns the range for the closes syntax node enclosing the given range.
2744    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2745        let range = range.start.to_offset(self)..range.end.to_offset(self);
2746        let mut result: Option<Range<usize>> = None;
2747        'outer: for layer in self
2748            .syntax
2749            .layers_for_range(range.clone(), &self.text, true)
2750        {
2751            let mut cursor = layer.node().walk();
2752
2753            // Descend to the first leaf that touches the start of the range,
2754            // and if the range is non-empty, extends beyond the start.
2755            while cursor.goto_first_child_for_byte(range.start).is_some() {
2756                if !range.is_empty() && cursor.node().end_byte() == range.start {
2757                    cursor.goto_next_sibling();
2758                }
2759            }
2760
2761            // Ascend to the smallest ancestor that strictly contains the range.
2762            loop {
2763                let node_range = cursor.node().byte_range();
2764                if node_range.start <= range.start
2765                    && node_range.end >= range.end
2766                    && node_range.len() > range.len()
2767                {
2768                    break;
2769                }
2770                if !cursor.goto_parent() {
2771                    continue 'outer;
2772                }
2773            }
2774
2775            let left_node = cursor.node();
2776            let mut layer_result = left_node.byte_range();
2777
2778            // For an empty range, try to find another node immediately to the right of the range.
2779            if left_node.end_byte() == range.start {
2780                let mut right_node = None;
2781                while !cursor.goto_next_sibling() {
2782                    if !cursor.goto_parent() {
2783                        break;
2784                    }
2785                }
2786
2787                while cursor.node().start_byte() == range.start {
2788                    right_node = Some(cursor.node());
2789                    if !cursor.goto_first_child() {
2790                        break;
2791                    }
2792                }
2793
2794                // If there is a candidate node on both sides of the (empty) range, then
2795                // decide between the two by favoring a named node over an anonymous token.
2796                // If both nodes are the same in that regard, favor the right one.
2797                if let Some(right_node) = right_node {
2798                    if right_node.is_named() || !left_node.is_named() {
2799                        layer_result = right_node.byte_range();
2800                    }
2801                }
2802            }
2803
2804            if let Some(previous_result) = &result {
2805                if previous_result.len() < layer_result.len() {
2806                    continue;
2807                }
2808            }
2809            result = Some(layer_result);
2810        }
2811
2812        result
2813    }
2814
2815    /// Returns the outline for the buffer.
2816    ///
2817    /// This method allows passing an optional [SyntaxTheme] to
2818    /// syntax-highlight the returned symbols.
2819    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2820        self.outline_items_containing(0..self.len(), true, theme)
2821            .map(Outline::new)
2822    }
2823
2824    /// Returns all the symbols that contain the given position.
2825    ///
2826    /// This method allows passing an optional [SyntaxTheme] to
2827    /// syntax-highlight the returned symbols.
2828    pub fn symbols_containing<T: ToOffset>(
2829        &self,
2830        position: T,
2831        theme: Option<&SyntaxTheme>,
2832    ) -> Option<Vec<OutlineItem<Anchor>>> {
2833        let position = position.to_offset(self);
2834        let mut items = self.outline_items_containing(
2835            position.saturating_sub(1)..self.len().min(position + 1),
2836            false,
2837            theme,
2838        )?;
2839        let mut prev_depth = None;
2840        items.retain(|item| {
2841            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
2842            prev_depth = Some(item.depth);
2843            result
2844        });
2845        Some(items)
2846    }
2847
2848    pub fn outline_items_containing<T: ToOffset>(
2849        &self,
2850        range: Range<T>,
2851        include_extra_context: bool,
2852        theme: Option<&SyntaxTheme>,
2853    ) -> Option<Vec<OutlineItem<Anchor>>> {
2854        let range = range.to_offset(self);
2855        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2856            grammar.outline_config.as_ref().map(|c| &c.query)
2857        });
2858        let configs = matches
2859            .grammars()
2860            .iter()
2861            .map(|g| g.outline_config.as_ref().unwrap())
2862            .collect::<Vec<_>>();
2863
2864        let mut items = Vec::new();
2865        let mut annotation_row_ranges: Vec<Range<u32>> = Vec::new();
2866        while let Some(mat) = matches.peek() {
2867            let config = &configs[mat.grammar_index];
2868            if let Some(item) =
2869                self.next_outline_item(config, &mat, &range, include_extra_context, theme)
2870            {
2871                items.push(item);
2872            } else if let Some(capture) = mat
2873                .captures
2874                .iter()
2875                .find(|capture| Some(capture.index) == config.annotation_capture_ix)
2876            {
2877                let capture_range = capture.node.start_position()..capture.node.end_position();
2878                let mut capture_row_range =
2879                    capture_range.start.row as u32..capture_range.end.row as u32;
2880                if capture_range.end.row > capture_range.start.row && capture_range.end.column == 0
2881                {
2882                    capture_row_range.end -= 1;
2883                }
2884                if let Some(last_row_range) = annotation_row_ranges.last_mut() {
2885                    if last_row_range.end >= capture_row_range.start.saturating_sub(1) {
2886                        last_row_range.end = capture_row_range.end;
2887                    } else {
2888                        annotation_row_ranges.push(capture_row_range);
2889                    }
2890                } else {
2891                    annotation_row_ranges.push(capture_row_range);
2892                }
2893            }
2894            matches.advance();
2895        }
2896
2897        items.sort_by_key(|item| (item.range.start, Reverse(item.range.end)));
2898
2899        // Assign depths based on containment relationships and convert to anchors.
2900        let mut item_ends_stack = Vec::<Point>::new();
2901        let mut anchor_items = Vec::new();
2902        let mut annotation_row_ranges = annotation_row_ranges.into_iter().peekable();
2903        for item in items {
2904            while let Some(last_end) = item_ends_stack.last().copied() {
2905                if last_end < item.range.end {
2906                    item_ends_stack.pop();
2907                } else {
2908                    break;
2909                }
2910            }
2911
2912            let mut annotation_row_range = None;
2913            while let Some(next_annotation_row_range) = annotation_row_ranges.peek() {
2914                let row_preceding_item = item.range.start.row.saturating_sub(1);
2915                if next_annotation_row_range.end < row_preceding_item {
2916                    annotation_row_ranges.next();
2917                } else {
2918                    if next_annotation_row_range.end == row_preceding_item {
2919                        annotation_row_range = Some(next_annotation_row_range.clone());
2920                        annotation_row_ranges.next();
2921                    }
2922                    break;
2923                }
2924            }
2925
2926            anchor_items.push(OutlineItem {
2927                depth: item_ends_stack.len(),
2928                range: self.anchor_after(item.range.start)..self.anchor_before(item.range.end),
2929                text: item.text,
2930                highlight_ranges: item.highlight_ranges,
2931                name_ranges: item.name_ranges,
2932                body_range: item.body_range.map(|body_range| {
2933                    self.anchor_after(body_range.start)..self.anchor_before(body_range.end)
2934                }),
2935                annotation_range: annotation_row_range.map(|annotation_range| {
2936                    self.anchor_after(Point::new(annotation_range.start, 0))
2937                        ..self.anchor_before(Point::new(
2938                            annotation_range.end,
2939                            self.line_len(annotation_range.end),
2940                        ))
2941                }),
2942            });
2943            item_ends_stack.push(item.range.end);
2944        }
2945
2946        Some(anchor_items)
2947    }
2948
2949    fn next_outline_item(
2950        &self,
2951        config: &OutlineConfig,
2952        mat: &SyntaxMapMatch,
2953        range: &Range<usize>,
2954        include_extra_context: bool,
2955        theme: Option<&SyntaxTheme>,
2956    ) -> Option<OutlineItem<Point>> {
2957        let item_node = mat.captures.iter().find_map(|cap| {
2958            if cap.index == config.item_capture_ix {
2959                Some(cap.node)
2960            } else {
2961                None
2962            }
2963        })?;
2964
2965        let item_byte_range = item_node.byte_range();
2966        if item_byte_range.end < range.start || item_byte_range.start > range.end {
2967            return None;
2968        }
2969        let item_point_range = Point::from_ts_point(item_node.start_position())
2970            ..Point::from_ts_point(item_node.end_position());
2971
2972        let mut open_point = None;
2973        let mut close_point = None;
2974        let mut buffer_ranges = Vec::new();
2975        for capture in mat.captures {
2976            let node_is_name;
2977            if capture.index == config.name_capture_ix {
2978                node_is_name = true;
2979            } else if Some(capture.index) == config.context_capture_ix
2980                || (Some(capture.index) == config.extra_context_capture_ix && include_extra_context)
2981            {
2982                node_is_name = false;
2983            } else {
2984                if Some(capture.index) == config.open_capture_ix {
2985                    open_point = Some(Point::from_ts_point(capture.node.end_position()));
2986                } else if Some(capture.index) == config.close_capture_ix {
2987                    close_point = Some(Point::from_ts_point(capture.node.start_position()));
2988                }
2989
2990                continue;
2991            }
2992
2993            let mut range = capture.node.start_byte()..capture.node.end_byte();
2994            let start = capture.node.start_position();
2995            if capture.node.end_position().row > start.row {
2996                range.end = range.start + self.line_len(start.row as u32) as usize - start.column;
2997            }
2998
2999            if !range.is_empty() {
3000                buffer_ranges.push((range, node_is_name));
3001            }
3002        }
3003        if buffer_ranges.is_empty() {
3004            return None;
3005        }
3006        let mut text = String::new();
3007        let mut highlight_ranges = Vec::new();
3008        let mut name_ranges = Vec::new();
3009        let mut chunks = self.chunks(
3010            buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
3011            true,
3012        );
3013        let mut last_buffer_range_end = 0;
3014        for (buffer_range, is_name) in buffer_ranges {
3015            if !text.is_empty() && buffer_range.start > last_buffer_range_end {
3016                text.push(' ');
3017            }
3018            last_buffer_range_end = buffer_range.end;
3019            if is_name {
3020                let mut start = text.len();
3021                let end = start + buffer_range.len();
3022
3023                // When multiple names are captured, then the matcheable text
3024                // includes the whitespace in between the names.
3025                if !name_ranges.is_empty() {
3026                    start -= 1;
3027                }
3028
3029                name_ranges.push(start..end);
3030            }
3031
3032            let mut offset = buffer_range.start;
3033            chunks.seek(buffer_range.clone());
3034            for mut chunk in chunks.by_ref() {
3035                if chunk.text.len() > buffer_range.end - offset {
3036                    chunk.text = &chunk.text[0..(buffer_range.end - offset)];
3037                    offset = buffer_range.end;
3038                } else {
3039                    offset += chunk.text.len();
3040                }
3041                let style = chunk
3042                    .syntax_highlight_id
3043                    .zip(theme)
3044                    .and_then(|(highlight, theme)| highlight.style(theme));
3045                if let Some(style) = style {
3046                    let start = text.len();
3047                    let end = start + chunk.text.len();
3048                    highlight_ranges.push((start..end, style));
3049                }
3050                text.push_str(chunk.text);
3051                if offset >= buffer_range.end {
3052                    break;
3053                }
3054            }
3055        }
3056
3057        Some(OutlineItem {
3058            depth: 0, // We'll calculate the depth later
3059            range: item_point_range,
3060            text,
3061            highlight_ranges,
3062            name_ranges,
3063            body_range: open_point.zip(close_point).map(|(start, end)| start..end),
3064            annotation_range: None,
3065        })
3066    }
3067
3068    /// For each grammar in the language, runs the provided
3069    /// [tree_sitter::Query] against the given range.
3070    pub fn matches(
3071        &self,
3072        range: Range<usize>,
3073        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
3074    ) -> SyntaxMapMatches {
3075        self.syntax.matches(range, self, query)
3076    }
3077
3078    /// Returns bracket range pairs overlapping or adjacent to `range`
3079    pub fn bracket_ranges<T: ToOffset>(
3080        &self,
3081        range: Range<T>,
3082    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3083        // Find bracket pairs that *inclusively* contain the given range.
3084        let range = range.start.to_offset(self).saturating_sub(1)
3085            ..self.len().min(range.end.to_offset(self) + 1);
3086
3087        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3088            grammar.brackets_config.as_ref().map(|c| &c.query)
3089        });
3090        let configs = matches
3091            .grammars()
3092            .iter()
3093            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
3094            .collect::<Vec<_>>();
3095
3096        iter::from_fn(move || {
3097            while let Some(mat) = matches.peek() {
3098                let mut open = None;
3099                let mut close = None;
3100                let config = &configs[mat.grammar_index];
3101                for capture in mat.captures {
3102                    if capture.index == config.open_capture_ix {
3103                        open = Some(capture.node.byte_range());
3104                    } else if capture.index == config.close_capture_ix {
3105                        close = Some(capture.node.byte_range());
3106                    }
3107                }
3108
3109                matches.advance();
3110
3111                let Some((open, close)) = open.zip(close) else {
3112                    continue;
3113                };
3114
3115                let bracket_range = open.start..=close.end;
3116                if !bracket_range.overlaps(&range) {
3117                    continue;
3118                }
3119
3120                return Some((open, close));
3121            }
3122            None
3123        })
3124    }
3125
3126    /// Returns enclosing bracket ranges containing the given range
3127    pub fn enclosing_bracket_ranges<T: ToOffset>(
3128        &self,
3129        range: Range<T>,
3130    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3131        let range = range.start.to_offset(self)..range.end.to_offset(self);
3132
3133        self.bracket_ranges(range.clone())
3134            .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
3135    }
3136
3137    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3138    ///
3139    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3140    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3141        &self,
3142        range: Range<T>,
3143        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3144    ) -> Option<(Range<usize>, Range<usize>)> {
3145        let range = range.start.to_offset(self)..range.end.to_offset(self);
3146
3147        // Get the ranges of the innermost pair of brackets.
3148        let mut result: Option<(Range<usize>, Range<usize>)> = None;
3149
3150        for (open, close) in self.enclosing_bracket_ranges(range.clone()) {
3151            if let Some(range_filter) = range_filter {
3152                if !range_filter(open.clone(), close.clone()) {
3153                    continue;
3154                }
3155            }
3156
3157            let len = close.end - open.start;
3158
3159            if let Some((existing_open, existing_close)) = &result {
3160                let existing_len = existing_close.end - existing_open.start;
3161                if len > existing_len {
3162                    continue;
3163                }
3164            }
3165
3166            result = Some((open, close));
3167        }
3168
3169        result
3170    }
3171
3172    /// Returns anchor ranges for any matches of the redaction query.
3173    /// The buffer can be associated with multiple languages, and the redaction query associated with each
3174    /// will be run on the relevant section of the buffer.
3175    pub fn redacted_ranges<T: ToOffset>(
3176        &self,
3177        range: Range<T>,
3178    ) -> impl Iterator<Item = Range<usize>> + '_ {
3179        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3180        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3181            grammar
3182                .redactions_config
3183                .as_ref()
3184                .map(|config| &config.query)
3185        });
3186
3187        let configs = syntax_matches
3188            .grammars()
3189            .iter()
3190            .map(|grammar| grammar.redactions_config.as_ref())
3191            .collect::<Vec<_>>();
3192
3193        iter::from_fn(move || {
3194            let redacted_range = syntax_matches
3195                .peek()
3196                .and_then(|mat| {
3197                    configs[mat.grammar_index].and_then(|config| {
3198                        mat.captures
3199                            .iter()
3200                            .find(|capture| capture.index == config.redaction_capture_ix)
3201                    })
3202                })
3203                .map(|mat| mat.node.byte_range());
3204            syntax_matches.advance();
3205            redacted_range
3206        })
3207    }
3208
3209    pub fn injections_intersecting_range<T: ToOffset>(
3210        &self,
3211        range: Range<T>,
3212    ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3213        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3214
3215        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3216            grammar
3217                .injection_config
3218                .as_ref()
3219                .map(|config| &config.query)
3220        });
3221
3222        let configs = syntax_matches
3223            .grammars()
3224            .iter()
3225            .map(|grammar| grammar.injection_config.as_ref())
3226            .collect::<Vec<_>>();
3227
3228        iter::from_fn(move || {
3229            let ranges = syntax_matches.peek().and_then(|mat| {
3230                let config = &configs[mat.grammar_index]?;
3231                let content_capture_range = mat.captures.iter().find_map(|capture| {
3232                    if capture.index == config.content_capture_ix {
3233                        Some(capture.node.byte_range())
3234                    } else {
3235                        None
3236                    }
3237                })?;
3238                let language = self.language_at(content_capture_range.start)?;
3239                Some((content_capture_range, language))
3240            });
3241            syntax_matches.advance();
3242            ranges
3243        })
3244    }
3245
3246    pub fn runnable_ranges(
3247        &self,
3248        range: Range<Anchor>,
3249    ) -> impl Iterator<Item = RunnableRange> + '_ {
3250        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3251
3252        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3253            grammar.runnable_config.as_ref().map(|config| &config.query)
3254        });
3255
3256        let test_configs = syntax_matches
3257            .grammars()
3258            .iter()
3259            .map(|grammar| grammar.runnable_config.as_ref())
3260            .collect::<Vec<_>>();
3261
3262        iter::from_fn(move || loop {
3263            let mat = syntax_matches.peek()?;
3264
3265            let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3266                let mut run_range = None;
3267                let full_range = mat.captures.iter().fold(
3268                    Range {
3269                        start: usize::MAX,
3270                        end: 0,
3271                    },
3272                    |mut acc, next| {
3273                        let byte_range = next.node.byte_range();
3274                        if acc.start > byte_range.start {
3275                            acc.start = byte_range.start;
3276                        }
3277                        if acc.end < byte_range.end {
3278                            acc.end = byte_range.end;
3279                        }
3280                        acc
3281                    },
3282                );
3283                if full_range.start > full_range.end {
3284                    // We did not find a full spanning range of this match.
3285                    return None;
3286                }
3287                let extra_captures: SmallVec<[_; 1]> =
3288                    SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3289                        test_configs
3290                            .extra_captures
3291                            .get(capture.index as usize)
3292                            .cloned()
3293                            .and_then(|tag_name| match tag_name {
3294                                RunnableCapture::Named(name) => {
3295                                    Some((capture.node.byte_range(), name))
3296                                }
3297                                RunnableCapture::Run => {
3298                                    let _ = run_range.insert(capture.node.byte_range());
3299                                    None
3300                                }
3301                            })
3302                    }));
3303                let run_range = run_range?;
3304                let tags = test_configs
3305                    .query
3306                    .property_settings(mat.pattern_index)
3307                    .iter()
3308                    .filter_map(|property| {
3309                        if *property.key == *"tag" {
3310                            property
3311                                .value
3312                                .as_ref()
3313                                .map(|value| RunnableTag(value.to_string().into()))
3314                        } else {
3315                            None
3316                        }
3317                    })
3318                    .collect();
3319                let extra_captures = extra_captures
3320                    .into_iter()
3321                    .map(|(range, name)| {
3322                        (
3323                            name.to_string(),
3324                            self.text_for_range(range.clone()).collect::<String>(),
3325                        )
3326                    })
3327                    .collect();
3328                // All tags should have the same range.
3329                Some(RunnableRange {
3330                    run_range,
3331                    full_range,
3332                    runnable: Runnable {
3333                        tags,
3334                        language: mat.language,
3335                        buffer: self.remote_id(),
3336                    },
3337                    extra_captures,
3338                    buffer_id: self.remote_id(),
3339                })
3340            });
3341
3342            syntax_matches.advance();
3343            if test_range.is_some() {
3344                // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
3345                // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
3346                return test_range;
3347            }
3348        })
3349    }
3350
3351    pub fn indent_guides_in_range(
3352        &self,
3353        range: Range<Anchor>,
3354        ignore_disabled_for_language: bool,
3355        cx: &AppContext,
3356    ) -> Vec<IndentGuide> {
3357        let language_settings = language_settings(self.language(), self.file.as_ref(), cx);
3358        let settings = language_settings.indent_guides;
3359        if !ignore_disabled_for_language && !settings.enabled {
3360            return Vec::new();
3361        }
3362        let tab_size = language_settings.tab_size.get() as u32;
3363
3364        let start_row = range.start.to_point(self).row;
3365        let end_row = range.end.to_point(self).row;
3366        let row_range = start_row..end_row + 1;
3367
3368        let mut row_indents = self.line_indents_in_row_range(row_range.clone());
3369
3370        let mut result_vec = Vec::new();
3371        let mut indent_stack = SmallVec::<[IndentGuide; 8]>::new();
3372
3373        while let Some((first_row, mut line_indent)) = row_indents.next() {
3374            let current_depth = indent_stack.len() as u32;
3375
3376            // When encountering empty, continue until found useful line indent
3377            // then add to the indent stack with the depth found
3378            let mut found_indent = false;
3379            let mut last_row = first_row;
3380            if line_indent.is_line_empty() {
3381                let mut trailing_row = end_row;
3382                while !found_indent {
3383                    let (target_row, new_line_indent) =
3384                        if let Some(display_row) = row_indents.next() {
3385                            display_row
3386                        } else {
3387                            // This means we reached the end of the given range and found empty lines at the end.
3388                            // We need to traverse further until we find a non-empty line to know if we need to add
3389                            // an indent guide for the last visible indent.
3390                            trailing_row += 1;
3391
3392                            const TRAILING_ROW_SEARCH_LIMIT: u32 = 25;
3393                            if trailing_row > self.max_point().row
3394                                || trailing_row > end_row + TRAILING_ROW_SEARCH_LIMIT
3395                            {
3396                                break;
3397                            }
3398                            let new_line_indent = self.line_indent_for_row(trailing_row);
3399                            (trailing_row, new_line_indent)
3400                        };
3401
3402                    if new_line_indent.is_line_empty() {
3403                        continue;
3404                    }
3405                    last_row = target_row.min(end_row);
3406                    line_indent = new_line_indent;
3407                    found_indent = true;
3408                    break;
3409                }
3410            } else {
3411                found_indent = true
3412            }
3413
3414            let depth = if found_indent {
3415                line_indent.len(tab_size) / tab_size
3416                    + ((line_indent.len(tab_size) % tab_size) > 0) as u32
3417            } else {
3418                current_depth
3419            };
3420
3421            if depth < current_depth {
3422                for _ in 0..(current_depth - depth) {
3423                    let mut indent = indent_stack.pop().unwrap();
3424                    if last_row != first_row {
3425                        // In this case, we landed on an empty row, had to seek forward,
3426                        // and discovered that the indent we where on is ending.
3427                        // This means that the last display row must
3428                        // be on line that ends this indent range, so we
3429                        // should display the range up to the first non-empty line
3430                        indent.end_row = first_row.saturating_sub(1);
3431                    }
3432
3433                    result_vec.push(indent)
3434                }
3435            } else if depth > current_depth {
3436                for next_depth in current_depth..depth {
3437                    indent_stack.push(IndentGuide {
3438                        buffer_id: self.remote_id(),
3439                        start_row: first_row,
3440                        end_row: last_row,
3441                        depth: next_depth,
3442                        tab_size,
3443                        settings,
3444                    });
3445                }
3446            }
3447
3448            for indent in indent_stack.iter_mut() {
3449                indent.end_row = last_row;
3450            }
3451        }
3452
3453        result_vec.extend(indent_stack);
3454
3455        result_vec
3456    }
3457
3458    pub async fn enclosing_indent(
3459        &self,
3460        mut buffer_row: BufferRow,
3461    ) -> Option<(Range<BufferRow>, LineIndent)> {
3462        let max_row = self.max_point().row;
3463        if buffer_row >= max_row {
3464            return None;
3465        }
3466
3467        let mut target_indent = self.line_indent_for_row(buffer_row);
3468
3469        // If the current row is at the start of an indented block, we want to return this
3470        // block as the enclosing indent.
3471        if !target_indent.is_line_empty() && buffer_row < max_row {
3472            let next_line_indent = self.line_indent_for_row(buffer_row + 1);
3473            if !next_line_indent.is_line_empty()
3474                && target_indent.raw_len() < next_line_indent.raw_len()
3475            {
3476                target_indent = next_line_indent;
3477                buffer_row += 1;
3478            }
3479        }
3480
3481        const SEARCH_ROW_LIMIT: u32 = 25000;
3482        const SEARCH_WHITESPACE_ROW_LIMIT: u32 = 2500;
3483        const YIELD_INTERVAL: u32 = 100;
3484
3485        let mut accessed_row_counter = 0;
3486
3487        // If there is a blank line at the current row, search for the next non indented lines
3488        if target_indent.is_line_empty() {
3489            let start = buffer_row.saturating_sub(SEARCH_WHITESPACE_ROW_LIMIT);
3490            let end = (max_row + 1).min(buffer_row + SEARCH_WHITESPACE_ROW_LIMIT);
3491
3492            let mut non_empty_line_above = None;
3493            for (row, indent) in self
3494                .text
3495                .reversed_line_indents_in_row_range(start..buffer_row)
3496            {
3497                accessed_row_counter += 1;
3498                if accessed_row_counter == YIELD_INTERVAL {
3499                    accessed_row_counter = 0;
3500                    yield_now().await;
3501                }
3502                if !indent.is_line_empty() {
3503                    non_empty_line_above = Some((row, indent));
3504                    break;
3505                }
3506            }
3507
3508            let mut non_empty_line_below = None;
3509            for (row, indent) in self.text.line_indents_in_row_range((buffer_row + 1)..end) {
3510                accessed_row_counter += 1;
3511                if accessed_row_counter == YIELD_INTERVAL {
3512                    accessed_row_counter = 0;
3513                    yield_now().await;
3514                }
3515                if !indent.is_line_empty() {
3516                    non_empty_line_below = Some((row, indent));
3517                    break;
3518                }
3519            }
3520
3521            let (row, indent) = match (non_empty_line_above, non_empty_line_below) {
3522                (Some((above_row, above_indent)), Some((below_row, below_indent))) => {
3523                    if above_indent.raw_len() >= below_indent.raw_len() {
3524                        (above_row, above_indent)
3525                    } else {
3526                        (below_row, below_indent)
3527                    }
3528                }
3529                (Some(above), None) => above,
3530                (None, Some(below)) => below,
3531                _ => return None,
3532            };
3533
3534            target_indent = indent;
3535            buffer_row = row;
3536        }
3537
3538        let start = buffer_row.saturating_sub(SEARCH_ROW_LIMIT);
3539        let end = (max_row + 1).min(buffer_row + SEARCH_ROW_LIMIT);
3540
3541        let mut start_indent = None;
3542        for (row, indent) in self
3543            .text
3544            .reversed_line_indents_in_row_range(start..buffer_row)
3545        {
3546            accessed_row_counter += 1;
3547            if accessed_row_counter == YIELD_INTERVAL {
3548                accessed_row_counter = 0;
3549                yield_now().await;
3550            }
3551            if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
3552                start_indent = Some((row, indent));
3553                break;
3554            }
3555        }
3556        let (start_row, start_indent_size) = start_indent?;
3557
3558        let mut end_indent = (end, None);
3559        for (row, indent) in self.text.line_indents_in_row_range((buffer_row + 1)..end) {
3560            accessed_row_counter += 1;
3561            if accessed_row_counter == YIELD_INTERVAL {
3562                accessed_row_counter = 0;
3563                yield_now().await;
3564            }
3565            if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
3566                end_indent = (row.saturating_sub(1), Some(indent));
3567                break;
3568            }
3569        }
3570        let (end_row, end_indent_size) = end_indent;
3571
3572        let indent = if let Some(end_indent_size) = end_indent_size {
3573            if start_indent_size.raw_len() > end_indent_size.raw_len() {
3574                start_indent_size
3575            } else {
3576                end_indent_size
3577            }
3578        } else {
3579            start_indent_size
3580        };
3581
3582        Some((start_row..end_row, indent))
3583    }
3584
3585    /// Returns selections for remote peers intersecting the given range.
3586    #[allow(clippy::type_complexity)]
3587    pub fn selections_in_range(
3588        &self,
3589        range: Range<Anchor>,
3590        include_local: bool,
3591    ) -> impl Iterator<
3592        Item = (
3593            ReplicaId,
3594            bool,
3595            CursorShape,
3596            impl Iterator<Item = &Selection<Anchor>> + '_,
3597        ),
3598    > + '_ {
3599        self.remote_selections
3600            .iter()
3601            .filter(move |(replica_id, set)| {
3602                (include_local || **replica_id != self.text.replica_id())
3603                    && !set.selections.is_empty()
3604            })
3605            .map(move |(replica_id, set)| {
3606                let start_ix = match set.selections.binary_search_by(|probe| {
3607                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
3608                }) {
3609                    Ok(ix) | Err(ix) => ix,
3610                };
3611                let end_ix = match set.selections.binary_search_by(|probe| {
3612                    probe.start.cmp(&range.end, self).then(Ordering::Less)
3613                }) {
3614                    Ok(ix) | Err(ix) => ix,
3615                };
3616
3617                (
3618                    *replica_id,
3619                    set.line_mode,
3620                    set.cursor_shape,
3621                    set.selections[start_ix..end_ix].iter(),
3622                )
3623            })
3624    }
3625
3626    /// Whether the buffer contains any git changes.
3627    pub fn has_git_diff(&self) -> bool {
3628        !self.git_diff.is_empty()
3629    }
3630
3631    /// Returns all the Git diff hunks intersecting the given
3632    /// row range.
3633    pub fn git_diff_hunks_in_row_range(
3634        &self,
3635        range: Range<BufferRow>,
3636    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3637        self.git_diff.hunks_in_row_range(range, self)
3638    }
3639
3640    /// Returns all the Git diff hunks intersecting the given
3641    /// range.
3642    pub fn git_diff_hunks_intersecting_range(
3643        &self,
3644        range: Range<Anchor>,
3645    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3646        self.git_diff.hunks_intersecting_range(range, self)
3647    }
3648
3649    /// Returns all the Git diff hunks intersecting the given
3650    /// range, in reverse order.
3651    pub fn git_diff_hunks_intersecting_range_rev(
3652        &self,
3653        range: Range<Anchor>,
3654    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3655        self.git_diff.hunks_intersecting_range_rev(range, self)
3656    }
3657
3658    /// Returns if the buffer contains any diagnostics.
3659    pub fn has_diagnostics(&self) -> bool {
3660        !self.diagnostics.is_empty()
3661    }
3662
3663    /// Returns all the diagnostics intersecting the given range.
3664    pub fn diagnostics_in_range<'a, T, O>(
3665        &'a self,
3666        search_range: Range<T>,
3667        reversed: bool,
3668    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3669    where
3670        T: 'a + Clone + ToOffset,
3671        O: 'a + FromAnchor + Ord,
3672    {
3673        let mut iterators: Vec<_> = self
3674            .diagnostics
3675            .iter()
3676            .map(|(_, collection)| {
3677                collection
3678                    .range::<T, O>(search_range.clone(), self, true, reversed)
3679                    .peekable()
3680            })
3681            .collect();
3682
3683        std::iter::from_fn(move || {
3684            let (next_ix, _) = iterators
3685                .iter_mut()
3686                .enumerate()
3687                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
3688                .min_by(|(_, a), (_, b)| {
3689                    let cmp = a
3690                        .range
3691                        .start
3692                        .cmp(&b.range.start)
3693                        // when range is equal, sort by diagnostic severity
3694                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
3695                        // and stabilize order with group_id
3696                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
3697                    if reversed {
3698                        cmp.reverse()
3699                    } else {
3700                        cmp
3701                    }
3702                })?;
3703            iterators[next_ix].next()
3704        })
3705    }
3706
3707    /// Returns all the diagnostic groups associated with the given
3708    /// language server id. If no language server id is provided,
3709    /// all diagnostics groups are returned.
3710    pub fn diagnostic_groups(
3711        &self,
3712        language_server_id: Option<LanguageServerId>,
3713    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
3714        let mut groups = Vec::new();
3715
3716        if let Some(language_server_id) = language_server_id {
3717            if let Ok(ix) = self
3718                .diagnostics
3719                .binary_search_by_key(&language_server_id, |e| e.0)
3720            {
3721                self.diagnostics[ix]
3722                    .1
3723                    .groups(language_server_id, &mut groups, self);
3724            }
3725        } else {
3726            for (language_server_id, diagnostics) in self.diagnostics.iter() {
3727                diagnostics.groups(*language_server_id, &mut groups, self);
3728            }
3729        }
3730
3731        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
3732            let a_start = &group_a.entries[group_a.primary_ix].range.start;
3733            let b_start = &group_b.entries[group_b.primary_ix].range.start;
3734            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
3735        });
3736
3737        groups
3738    }
3739
3740    /// Returns an iterator over the diagnostics for the given group.
3741    pub fn diagnostic_group<'a, O>(
3742        &'a self,
3743        group_id: usize,
3744    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3745    where
3746        O: 'a + FromAnchor,
3747    {
3748        self.diagnostics
3749            .iter()
3750            .flat_map(move |(_, set)| set.group(group_id, self))
3751    }
3752
3753    /// An integer version number that accounts for all updates besides
3754    /// the buffer's text itself (which is versioned via a version vector).
3755    pub fn non_text_state_update_count(&self) -> usize {
3756        self.non_text_state_update_count
3757    }
3758
3759    /// Returns a snapshot of underlying file.
3760    pub fn file(&self) -> Option<&Arc<dyn File>> {
3761        self.file.as_ref()
3762    }
3763
3764    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
3765    pub fn resolve_file_path(&self, cx: &AppContext, include_root: bool) -> Option<PathBuf> {
3766        if let Some(file) = self.file() {
3767            if file.path().file_name().is_none() || include_root {
3768                Some(file.full_path(cx))
3769            } else {
3770                Some(file.path().to_path_buf())
3771            }
3772        } else {
3773            None
3774        }
3775    }
3776}
3777
3778fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
3779    indent_size_for_text(text.chars_at(Point::new(row, 0)))
3780}
3781
3782fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
3783    let mut result = IndentSize::spaces(0);
3784    for c in text {
3785        let kind = match c {
3786            ' ' => IndentKind::Space,
3787            '\t' => IndentKind::Tab,
3788            _ => break,
3789        };
3790        if result.len == 0 {
3791            result.kind = kind;
3792        }
3793        result.len += 1;
3794    }
3795    result
3796}
3797
3798impl Clone for BufferSnapshot {
3799    fn clone(&self) -> Self {
3800        Self {
3801            text: self.text.clone(),
3802            git_diff: self.git_diff.clone(),
3803            syntax: self.syntax.clone(),
3804            file: self.file.clone(),
3805            remote_selections: self.remote_selections.clone(),
3806            diagnostics: self.diagnostics.clone(),
3807            language: self.language.clone(),
3808            non_text_state_update_count: self.non_text_state_update_count,
3809        }
3810    }
3811}
3812
3813impl Deref for BufferSnapshot {
3814    type Target = text::BufferSnapshot;
3815
3816    fn deref(&self) -> &Self::Target {
3817        &self.text
3818    }
3819}
3820
3821unsafe impl<'a> Send for BufferChunks<'a> {}
3822
3823impl<'a> BufferChunks<'a> {
3824    pub(crate) fn new(
3825        text: &'a Rope,
3826        range: Range<usize>,
3827        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
3828        diagnostics: bool,
3829        buffer_snapshot: Option<&'a BufferSnapshot>,
3830    ) -> Self {
3831        let mut highlights = None;
3832        if let Some((captures, highlight_maps)) = syntax {
3833            highlights = Some(BufferChunkHighlights {
3834                captures,
3835                next_capture: None,
3836                stack: Default::default(),
3837                highlight_maps,
3838            })
3839        }
3840
3841        let diagnostic_endpoints = diagnostics.then(|| Vec::new().into_iter().peekable());
3842        let chunks = text.chunks_in_range(range.clone());
3843
3844        let mut this = BufferChunks {
3845            range,
3846            buffer_snapshot,
3847            chunks,
3848            diagnostic_endpoints,
3849            error_depth: 0,
3850            warning_depth: 0,
3851            information_depth: 0,
3852            hint_depth: 0,
3853            unnecessary_depth: 0,
3854            highlights,
3855        };
3856        this.initialize_diagnostic_endpoints();
3857        this
3858    }
3859
3860    /// Seeks to the given byte offset in the buffer.
3861    pub fn seek(&mut self, range: Range<usize>) {
3862        let old_range = std::mem::replace(&mut self.range, range.clone());
3863        self.chunks.set_range(self.range.clone());
3864        if let Some(highlights) = self.highlights.as_mut() {
3865            if old_range.start >= self.range.start && old_range.end <= self.range.end {
3866                // Reuse existing highlights stack, as the new range is a subrange of the old one.
3867                highlights
3868                    .stack
3869                    .retain(|(end_offset, _)| *end_offset > range.start);
3870                if let Some(capture) = &highlights.next_capture {
3871                    if range.start >= capture.node.start_byte() {
3872                        let next_capture_end = capture.node.end_byte();
3873                        if range.start < next_capture_end {
3874                            highlights.stack.push((
3875                                next_capture_end,
3876                                highlights.highlight_maps[capture.grammar_index].get(capture.index),
3877                            ));
3878                        }
3879                        highlights.next_capture.take();
3880                    }
3881                }
3882            } else if let Some(snapshot) = self.buffer_snapshot {
3883                let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
3884                *highlights = BufferChunkHighlights {
3885                    captures,
3886                    next_capture: None,
3887                    stack: Default::default(),
3888                    highlight_maps,
3889                };
3890            } else {
3891                // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
3892                // Seeking such BufferChunks is not supported.
3893                debug_assert!(false, "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot");
3894            }
3895
3896            highlights.captures.set_byte_range(self.range.clone());
3897            self.initialize_diagnostic_endpoints();
3898        }
3899    }
3900
3901    fn initialize_diagnostic_endpoints(&mut self) {
3902        if let Some(diagnostics) = self.diagnostic_endpoints.as_mut() {
3903            if let Some(buffer) = self.buffer_snapshot {
3904                let mut diagnostic_endpoints = Vec::new();
3905                for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
3906                    diagnostic_endpoints.push(DiagnosticEndpoint {
3907                        offset: entry.range.start,
3908                        is_start: true,
3909                        severity: entry.diagnostic.severity,
3910                        is_unnecessary: entry.diagnostic.is_unnecessary,
3911                    });
3912                    diagnostic_endpoints.push(DiagnosticEndpoint {
3913                        offset: entry.range.end,
3914                        is_start: false,
3915                        severity: entry.diagnostic.severity,
3916                        is_unnecessary: entry.diagnostic.is_unnecessary,
3917                    });
3918                }
3919                diagnostic_endpoints
3920                    .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
3921                *diagnostics = diagnostic_endpoints.into_iter().peekable();
3922            }
3923        }
3924    }
3925
3926    /// The current byte offset in the buffer.
3927    pub fn offset(&self) -> usize {
3928        self.range.start
3929    }
3930
3931    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
3932        let depth = match endpoint.severity {
3933            DiagnosticSeverity::ERROR => &mut self.error_depth,
3934            DiagnosticSeverity::WARNING => &mut self.warning_depth,
3935            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
3936            DiagnosticSeverity::HINT => &mut self.hint_depth,
3937            _ => return,
3938        };
3939        if endpoint.is_start {
3940            *depth += 1;
3941        } else {
3942            *depth -= 1;
3943        }
3944
3945        if endpoint.is_unnecessary {
3946            if endpoint.is_start {
3947                self.unnecessary_depth += 1;
3948            } else {
3949                self.unnecessary_depth -= 1;
3950            }
3951        }
3952    }
3953
3954    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
3955        if self.error_depth > 0 {
3956            Some(DiagnosticSeverity::ERROR)
3957        } else if self.warning_depth > 0 {
3958            Some(DiagnosticSeverity::WARNING)
3959        } else if self.information_depth > 0 {
3960            Some(DiagnosticSeverity::INFORMATION)
3961        } else if self.hint_depth > 0 {
3962            Some(DiagnosticSeverity::HINT)
3963        } else {
3964            None
3965        }
3966    }
3967
3968    fn current_code_is_unnecessary(&self) -> bool {
3969        self.unnecessary_depth > 0
3970    }
3971}
3972
3973impl<'a> Iterator for BufferChunks<'a> {
3974    type Item = Chunk<'a>;
3975
3976    fn next(&mut self) -> Option<Self::Item> {
3977        let mut next_capture_start = usize::MAX;
3978        let mut next_diagnostic_endpoint = usize::MAX;
3979
3980        if let Some(highlights) = self.highlights.as_mut() {
3981            while let Some((parent_capture_end, _)) = highlights.stack.last() {
3982                if *parent_capture_end <= self.range.start {
3983                    highlights.stack.pop();
3984                } else {
3985                    break;
3986                }
3987            }
3988
3989            if highlights.next_capture.is_none() {
3990                highlights.next_capture = highlights.captures.next();
3991            }
3992
3993            while let Some(capture) = highlights.next_capture.as_ref() {
3994                if self.range.start < capture.node.start_byte() {
3995                    next_capture_start = capture.node.start_byte();
3996                    break;
3997                } else {
3998                    let highlight_id =
3999                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
4000                    highlights
4001                        .stack
4002                        .push((capture.node.end_byte(), highlight_id));
4003                    highlights.next_capture = highlights.captures.next();
4004                }
4005            }
4006        }
4007
4008        let mut diagnostic_endpoints = std::mem::take(&mut self.diagnostic_endpoints);
4009        if let Some(diagnostic_endpoints) = diagnostic_endpoints.as_mut() {
4010            while let Some(endpoint) = diagnostic_endpoints.peek().copied() {
4011                if endpoint.offset <= self.range.start {
4012                    self.update_diagnostic_depths(endpoint);
4013                    diagnostic_endpoints.next();
4014                } else {
4015                    next_diagnostic_endpoint = endpoint.offset;
4016                    break;
4017                }
4018            }
4019        }
4020        self.diagnostic_endpoints = diagnostic_endpoints;
4021
4022        if let Some(chunk) = self.chunks.peek() {
4023            let chunk_start = self.range.start;
4024            let mut chunk_end = (self.chunks.offset() + chunk.len())
4025                .min(next_capture_start)
4026                .min(next_diagnostic_endpoint);
4027            let mut highlight_id = None;
4028            if let Some(highlights) = self.highlights.as_ref() {
4029                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
4030                    chunk_end = chunk_end.min(*parent_capture_end);
4031                    highlight_id = Some(*parent_highlight_id);
4032                }
4033            }
4034
4035            let slice =
4036                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
4037            self.range.start = chunk_end;
4038            if self.range.start == self.chunks.offset() + chunk.len() {
4039                self.chunks.next().unwrap();
4040            }
4041
4042            Some(Chunk {
4043                text: slice,
4044                syntax_highlight_id: highlight_id,
4045                diagnostic_severity: self.current_diagnostic_severity(),
4046                is_unnecessary: self.current_code_is_unnecessary(),
4047                ..Default::default()
4048            })
4049        } else {
4050            None
4051        }
4052    }
4053}
4054
4055impl operation_queue::Operation for Operation {
4056    fn lamport_timestamp(&self) -> clock::Lamport {
4057        match self {
4058            Operation::Buffer(_) => {
4059                unreachable!("buffer operations should never be deferred at this layer")
4060            }
4061            Operation::UpdateDiagnostics {
4062                lamport_timestamp, ..
4063            }
4064            | Operation::UpdateSelections {
4065                lamport_timestamp, ..
4066            }
4067            | Operation::UpdateCompletionTriggers {
4068                lamport_timestamp, ..
4069            } => *lamport_timestamp,
4070        }
4071    }
4072}
4073
4074impl Default for Diagnostic {
4075    fn default() -> Self {
4076        Self {
4077            source: Default::default(),
4078            code: None,
4079            severity: DiagnosticSeverity::ERROR,
4080            message: Default::default(),
4081            group_id: 0,
4082            is_primary: false,
4083            is_disk_based: false,
4084            is_unnecessary: false,
4085            data: None,
4086        }
4087    }
4088}
4089
4090impl IndentSize {
4091    /// Returns an [IndentSize] representing the given spaces.
4092    pub fn spaces(len: u32) -> Self {
4093        Self {
4094            len,
4095            kind: IndentKind::Space,
4096        }
4097    }
4098
4099    /// Returns an [IndentSize] representing a tab.
4100    pub fn tab() -> Self {
4101        Self {
4102            len: 1,
4103            kind: IndentKind::Tab,
4104        }
4105    }
4106
4107    /// An iterator over the characters represented by this [IndentSize].
4108    pub fn chars(&self) -> impl Iterator<Item = char> {
4109        iter::repeat(self.char()).take(self.len as usize)
4110    }
4111
4112    /// The character representation of this [IndentSize].
4113    pub fn char(&self) -> char {
4114        match self.kind {
4115            IndentKind::Space => ' ',
4116            IndentKind::Tab => '\t',
4117        }
4118    }
4119
4120    /// Consumes the current [IndentSize] and returns a new one that has
4121    /// been shrunk or enlarged by the given size along the given direction.
4122    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4123        match direction {
4124            Ordering::Less => {
4125                if self.kind == size.kind && self.len >= size.len {
4126                    self.len -= size.len;
4127                }
4128            }
4129            Ordering::Equal => {}
4130            Ordering::Greater => {
4131                if self.len == 0 {
4132                    self = size;
4133                } else if self.kind == size.kind {
4134                    self.len += size.len;
4135                }
4136            }
4137        }
4138        self
4139    }
4140}
4141
4142#[cfg(any(test, feature = "test-support"))]
4143pub struct TestFile {
4144    pub path: Arc<Path>,
4145    pub root_name: String,
4146}
4147
4148#[cfg(any(test, feature = "test-support"))]
4149impl File for TestFile {
4150    fn path(&self) -> &Arc<Path> {
4151        &self.path
4152    }
4153
4154    fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
4155        PathBuf::from(&self.root_name).join(self.path.as_ref())
4156    }
4157
4158    fn as_local(&self) -> Option<&dyn LocalFile> {
4159        None
4160    }
4161
4162    fn mtime(&self) -> Option<SystemTime> {
4163        unimplemented!()
4164    }
4165
4166    fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
4167        self.path().file_name().unwrap_or(self.root_name.as_ref())
4168    }
4169
4170    fn worktree_id(&self) -> usize {
4171        0
4172    }
4173
4174    fn is_deleted(&self) -> bool {
4175        unimplemented!()
4176    }
4177
4178    fn as_any(&self) -> &dyn std::any::Any {
4179        unimplemented!()
4180    }
4181
4182    fn to_proto(&self, _: &AppContext) -> rpc::proto::File {
4183        unimplemented!()
4184    }
4185
4186    fn is_private(&self) -> bool {
4187        false
4188    }
4189}
4190
4191pub(crate) fn contiguous_ranges(
4192    values: impl Iterator<Item = u32>,
4193    max_len: usize,
4194) -> impl Iterator<Item = Range<u32>> {
4195    let mut values = values;
4196    let mut current_range: Option<Range<u32>> = None;
4197    std::iter::from_fn(move || loop {
4198        if let Some(value) = values.next() {
4199            if let Some(range) = &mut current_range {
4200                if value == range.end && range.len() < max_len {
4201                    range.end += 1;
4202                    continue;
4203                }
4204            }
4205
4206            let prev_range = current_range.clone();
4207            current_range = Some(value..(value + 1));
4208            if prev_range.is_some() {
4209                return prev_range;
4210            }
4211        } else {
4212            return current_range.take();
4213        }
4214    })
4215}
4216
4217/// Returns the [CharKind] for the given character. When a scope is provided,
4218/// the function checks if the character is considered a word character
4219/// based on the language scope's word character settings.
4220pub fn char_kind(scope: &Option<LanguageScope>, c: char) -> CharKind {
4221    if c.is_whitespace() {
4222        return CharKind::Whitespace;
4223    } else if c.is_alphanumeric() || c == '_' {
4224        return CharKind::Word;
4225    }
4226
4227    if let Some(scope) = scope {
4228        if let Some(characters) = scope.word_characters() {
4229            if characters.contains(&c) {
4230                return CharKind::Word;
4231            }
4232        }
4233    }
4234
4235    CharKind::Punctuation
4236}
4237
4238/// Find all of the ranges of whitespace that occur at the ends of lines
4239/// in the given rope.
4240///
4241/// This could also be done with a regex search, but this implementation
4242/// avoids copying text.
4243pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4244    let mut ranges = Vec::new();
4245
4246    let mut offset = 0;
4247    let mut prev_chunk_trailing_whitespace_range = 0..0;
4248    for chunk in rope.chunks() {
4249        let mut prev_line_trailing_whitespace_range = 0..0;
4250        for (i, line) in chunk.split('\n').enumerate() {
4251            let line_end_offset = offset + line.len();
4252            let trimmed_line_len = line.trim_end_matches(|c| matches!(c, ' ' | '\t')).len();
4253            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4254
4255            if i == 0 && trimmed_line_len == 0 {
4256                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4257            }
4258            if !prev_line_trailing_whitespace_range.is_empty() {
4259                ranges.push(prev_line_trailing_whitespace_range);
4260            }
4261
4262            offset = line_end_offset + 1;
4263            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4264        }
4265
4266        offset -= 1;
4267        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4268    }
4269
4270    if !prev_chunk_trailing_whitespace_range.is_empty() {
4271        ranges.push(prev_chunk_trailing_whitespace_range);
4272    }
4273
4274    ranges
4275}