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