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