buffer.rs

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