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