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(Debug, 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                // Compute new suggestions for each line, but only include them in the result
1424                // if they differ from the old suggestion for that line.
1425                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1426                let mut language_indent_size = IndentSize::default();
1427                for (row_range, original_indent_column) in row_ranges {
1428                    let new_edited_row_range = if request.is_block_mode {
1429                        row_range.start..row_range.start + 1
1430                    } else {
1431                        row_range.clone()
1432                    };
1433
1434                    let suggestions = snapshot
1435                        .suggest_autoindents(new_edited_row_range.clone())
1436                        .into_iter()
1437                        .flatten();
1438                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
1439                        if let Some(suggestion) = suggestion {
1440                            // Find the indent size based on the language for this row.
1441                            while let Some((row, size)) = language_indent_sizes.peek() {
1442                                if *row > new_row {
1443                                    break;
1444                                }
1445                                language_indent_size = *size;
1446                                language_indent_sizes.next();
1447                            }
1448
1449                            let suggested_indent = indent_sizes
1450                                .get(&suggestion.basis_row)
1451                                .copied()
1452                                .unwrap_or_else(|| {
1453                                    snapshot.indent_size_for_line(suggestion.basis_row)
1454                                })
1455                                .with_delta(suggestion.delta, language_indent_size);
1456                            if old_suggestions.get(&new_row).map_or(
1457                                true,
1458                                |(old_indentation, was_within_error)| {
1459                                    suggested_indent != *old_indentation
1460                                        && (!suggestion.within_error || *was_within_error)
1461                                },
1462                            ) {
1463                                indent_sizes.insert(new_row, suggested_indent);
1464                            }
1465                        }
1466                    }
1467
1468                    if let (true, Some(original_indent_column)) =
1469                        (request.is_block_mode, original_indent_column)
1470                    {
1471                        let new_indent = indent_sizes
1472                            .get(&row_range.start)
1473                            .copied()
1474                            .unwrap_or_else(|| snapshot.indent_size_for_line(row_range.start));
1475                        let delta = new_indent.len as i64 - original_indent_column as i64;
1476                        if delta != 0 {
1477                            for row in row_range.skip(1) {
1478                                indent_sizes.entry(row).or_insert_with(|| {
1479                                    let mut size = snapshot.indent_size_for_line(row);
1480                                    if size.kind == new_indent.kind {
1481                                        match delta.cmp(&0) {
1482                                            Ordering::Greater => size.len += delta as u32,
1483                                            Ordering::Less => {
1484                                                size.len = size.len.saturating_sub(-delta as u32)
1485                                            }
1486                                            Ordering::Equal => {}
1487                                        }
1488                                    }
1489                                    size
1490                                });
1491                            }
1492                        }
1493                    }
1494
1495                    yield_now().await;
1496                }
1497            }
1498
1499            indent_sizes
1500        })
1501    }
1502
1503    fn apply_autoindents(
1504        &mut self,
1505        indent_sizes: BTreeMap<u32, IndentSize>,
1506        cx: &mut ModelContext<Self>,
1507    ) {
1508        self.autoindent_requests.clear();
1509
1510        let edits: Vec<_> = indent_sizes
1511            .into_iter()
1512            .filter_map(|(row, indent_size)| {
1513                let current_size = indent_size_for_line(self, row);
1514                Self::edit_for_indent_size_adjustment(row, current_size, indent_size)
1515            })
1516            .collect();
1517
1518        let preserve_preview = self.preserve_preview();
1519        self.edit(edits, None, cx);
1520        if preserve_preview {
1521            self.refresh_preview();
1522        }
1523    }
1524
1525    /// Create a minimal edit that will cause the given row to be indented
1526    /// with the given size. After applying this edit, the length of the line
1527    /// will always be at least `new_size.len`.
1528    pub fn edit_for_indent_size_adjustment(
1529        row: u32,
1530        current_size: IndentSize,
1531        new_size: IndentSize,
1532    ) -> Option<(Range<Point>, String)> {
1533        if new_size.kind == current_size.kind {
1534            match new_size.len.cmp(&current_size.len) {
1535                Ordering::Greater => {
1536                    let point = Point::new(row, 0);
1537                    Some((
1538                        point..point,
1539                        iter::repeat(new_size.char())
1540                            .take((new_size.len - current_size.len) as usize)
1541                            .collect::<String>(),
1542                    ))
1543                }
1544
1545                Ordering::Less => Some((
1546                    Point::new(row, 0)..Point::new(row, current_size.len - new_size.len),
1547                    String::new(),
1548                )),
1549
1550                Ordering::Equal => None,
1551            }
1552        } else {
1553            Some((
1554                Point::new(row, 0)..Point::new(row, current_size.len),
1555                iter::repeat(new_size.char())
1556                    .take(new_size.len as usize)
1557                    .collect::<String>(),
1558            ))
1559        }
1560    }
1561
1562    /// Spawns a background task that asynchronously computes a `Diff` between the buffer's text
1563    /// and the given new text.
1564    pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
1565        let old_text = self.as_rope().clone();
1566        let base_version = self.version();
1567        cx.background_executor()
1568            .spawn_labeled(*BUFFER_DIFF_TASK, async move {
1569                let old_text = old_text.to_string();
1570                let line_ending = LineEnding::detect(&new_text);
1571                LineEnding::normalize(&mut new_text);
1572
1573                let diff = TextDiff::from_chars(old_text.as_str(), new_text.as_str());
1574                let empty: Arc<str> = Arc::default();
1575
1576                let mut edits = Vec::new();
1577                let mut old_offset = 0;
1578                let mut new_offset = 0;
1579                let mut last_edit: Option<(Range<usize>, Range<usize>)> = None;
1580                for change in diff.iter_all_changes().map(Some).chain([None]) {
1581                    if let Some(change) = &change {
1582                        let len = change.value().len();
1583                        match change.tag() {
1584                            ChangeTag::Equal => {
1585                                old_offset += len;
1586                                new_offset += len;
1587                            }
1588                            ChangeTag::Delete => {
1589                                let old_end_offset = old_offset + len;
1590                                if let Some((last_old_range, _)) = &mut last_edit {
1591                                    last_old_range.end = old_end_offset;
1592                                } else {
1593                                    last_edit =
1594                                        Some((old_offset..old_end_offset, new_offset..new_offset));
1595                                }
1596                                old_offset = old_end_offset;
1597                            }
1598                            ChangeTag::Insert => {
1599                                let new_end_offset = new_offset + len;
1600                                if let Some((_, last_new_range)) = &mut last_edit {
1601                                    last_new_range.end = new_end_offset;
1602                                } else {
1603                                    last_edit =
1604                                        Some((old_offset..old_offset, new_offset..new_end_offset));
1605                                }
1606                                new_offset = new_end_offset;
1607                            }
1608                        }
1609                    }
1610
1611                    if let Some((old_range, new_range)) = &last_edit {
1612                        if old_offset > old_range.end
1613                            || new_offset > new_range.end
1614                            || change.is_none()
1615                        {
1616                            let text = if new_range.is_empty() {
1617                                empty.clone()
1618                            } else {
1619                                new_text[new_range.clone()].into()
1620                            };
1621                            edits.push((old_range.clone(), text));
1622                            last_edit.take();
1623                        }
1624                    }
1625                }
1626
1627                Diff {
1628                    base_version,
1629                    line_ending,
1630                    edits,
1631                }
1632            })
1633    }
1634
1635    /// Spawns a background task that searches the buffer for any whitespace
1636    /// at the ends of a lines, and returns a `Diff` that removes that whitespace.
1637    pub fn remove_trailing_whitespace(&self, cx: &AppContext) -> Task<Diff> {
1638        let old_text = self.as_rope().clone();
1639        let line_ending = self.line_ending();
1640        let base_version = self.version();
1641        cx.background_executor().spawn(async move {
1642            let ranges = trailing_whitespace_ranges(&old_text);
1643            let empty = Arc::<str>::from("");
1644            Diff {
1645                base_version,
1646                line_ending,
1647                edits: ranges
1648                    .into_iter()
1649                    .map(|range| (range, empty.clone()))
1650                    .collect(),
1651            }
1652        })
1653    }
1654
1655    /// Ensures that the buffer ends with a single newline character, and
1656    /// no other whitespace.
1657    pub fn ensure_final_newline(&mut self, cx: &mut ModelContext<Self>) {
1658        let len = self.len();
1659        let mut offset = len;
1660        for chunk in self.as_rope().reversed_chunks_in_range(0..len) {
1661            let non_whitespace_len = chunk
1662                .trim_end_matches(|c: char| c.is_ascii_whitespace())
1663                .len();
1664            offset -= chunk.len();
1665            offset += non_whitespace_len;
1666            if non_whitespace_len != 0 {
1667                if offset == len - 1 && chunk.get(non_whitespace_len..) == Some("\n") {
1668                    return;
1669                }
1670                break;
1671            }
1672        }
1673        self.edit([(offset..len, "\n")], None, cx);
1674    }
1675
1676    /// Applies a diff to the buffer. If the buffer has changed since the given diff was
1677    /// calculated, then adjust the diff to account for those changes, and discard any
1678    /// parts of the diff that conflict with those changes.
1679    pub fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1680        // Check for any edits to the buffer that have occurred since this diff
1681        // was computed.
1682        let snapshot = self.snapshot();
1683        let mut edits_since = snapshot.edits_since::<usize>(&diff.base_version).peekable();
1684        let mut delta = 0;
1685        let adjusted_edits = diff.edits.into_iter().filter_map(|(range, new_text)| {
1686            while let Some(edit_since) = edits_since.peek() {
1687                // If the edit occurs after a diff hunk, then it does not
1688                // affect that hunk.
1689                if edit_since.old.start > range.end {
1690                    break;
1691                }
1692                // If the edit precedes the diff hunk, then adjust the hunk
1693                // to reflect the edit.
1694                else if edit_since.old.end < range.start {
1695                    delta += edit_since.new_len() as i64 - edit_since.old_len() as i64;
1696                    edits_since.next();
1697                }
1698                // If the edit intersects a diff hunk, then discard that hunk.
1699                else {
1700                    return None;
1701                }
1702            }
1703
1704            let start = (range.start as i64 + delta) as usize;
1705            let end = (range.end as i64 + delta) as usize;
1706            Some((start..end, new_text))
1707        });
1708
1709        self.start_transaction();
1710        self.text.set_line_ending(diff.line_ending);
1711        self.edit(adjusted_edits, None, cx);
1712        self.end_transaction(cx)
1713    }
1714
1715    fn has_unsaved_edits(&self) -> bool {
1716        let (last_version, has_unsaved_edits) = self.has_unsaved_edits.take();
1717
1718        if last_version == self.version {
1719            self.has_unsaved_edits
1720                .set((last_version, has_unsaved_edits));
1721            return has_unsaved_edits;
1722        }
1723
1724        let has_edits = self.has_edits_since(&self.saved_version);
1725        self.has_unsaved_edits
1726            .set((self.version.clone(), has_edits));
1727        has_edits
1728    }
1729
1730    /// Checks if the buffer has unsaved changes.
1731    pub fn is_dirty(&self) -> bool {
1732        self.capability != Capability::ReadOnly
1733            && (self.has_conflict
1734                || self.has_unsaved_edits()
1735                || self
1736                    .file
1737                    .as_ref()
1738                    .map_or(false, |file| file.is_deleted() || !file.is_created()))
1739    }
1740
1741    /// Checks if the buffer and its file have both changed since the buffer
1742    /// was last saved or reloaded.
1743    pub fn has_conflict(&self) -> bool {
1744        self.has_conflict
1745            || self.file.as_ref().map_or(false, |file| {
1746                file.mtime() > self.saved_mtime && self.has_unsaved_edits()
1747            })
1748    }
1749
1750    /// Gets a [`Subscription`] that tracks all of the changes to the buffer's text.
1751    pub fn subscribe(&mut self) -> Subscription {
1752        self.text.subscribe()
1753    }
1754
1755    /// Starts a transaction, if one is not already in-progress. When undoing or
1756    /// redoing edits, all of the edits performed within a transaction are undone
1757    /// or redone together.
1758    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1759        self.start_transaction_at(Instant::now())
1760    }
1761
1762    /// Starts a transaction, providing the current time. Subsequent transactions
1763    /// that occur within a short period of time will be grouped together. This
1764    /// is controlled by the buffer's undo grouping duration.
1765    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1766        self.transaction_depth += 1;
1767        if self.was_dirty_before_starting_transaction.is_none() {
1768            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
1769        }
1770        self.text.start_transaction_at(now)
1771    }
1772
1773    /// Terminates the current transaction, if this is the outermost transaction.
1774    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1775        self.end_transaction_at(Instant::now(), cx)
1776    }
1777
1778    /// Terminates the current transaction, providing the current time. Subsequent transactions
1779    /// that occur within a short period of time will be grouped together. This
1780    /// is controlled by the buffer's undo grouping duration.
1781    pub fn end_transaction_at(
1782        &mut self,
1783        now: Instant,
1784        cx: &mut ModelContext<Self>,
1785    ) -> Option<TransactionId> {
1786        assert!(self.transaction_depth > 0);
1787        self.transaction_depth -= 1;
1788        let was_dirty = if self.transaction_depth == 0 {
1789            self.was_dirty_before_starting_transaction.take().unwrap()
1790        } else {
1791            false
1792        };
1793        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1794            self.did_edit(&start_version, was_dirty, cx);
1795            Some(transaction_id)
1796        } else {
1797            None
1798        }
1799    }
1800
1801    /// Manually add a transaction to the buffer's undo history.
1802    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1803        self.text.push_transaction(transaction, now);
1804    }
1805
1806    /// Prevent the last transaction from being grouped with any subsequent transactions,
1807    /// even if they occur with the buffer's undo grouping duration.
1808    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1809        self.text.finalize_last_transaction()
1810    }
1811
1812    /// Manually group all changes since a given transaction.
1813    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
1814        self.text.group_until_transaction(transaction_id);
1815    }
1816
1817    /// Manually remove a transaction from the buffer's undo history
1818    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1819        self.text.forget_transaction(transaction_id);
1820    }
1821
1822    /// Manually merge two adjacent transactions in the buffer's undo history.
1823    pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
1824        self.text.merge_transactions(transaction, destination);
1825    }
1826
1827    /// Waits for the buffer to receive operations with the given timestamps.
1828    pub fn wait_for_edits(
1829        &mut self,
1830        edit_ids: impl IntoIterator<Item = clock::Lamport>,
1831    ) -> impl Future<Output = Result<()>> {
1832        self.text.wait_for_edits(edit_ids)
1833    }
1834
1835    /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
1836    pub fn wait_for_anchors(
1837        &mut self,
1838        anchors: impl IntoIterator<Item = Anchor>,
1839    ) -> impl 'static + Future<Output = Result<()>> {
1840        self.text.wait_for_anchors(anchors)
1841    }
1842
1843    /// Waits for the buffer to receive operations up to the given version.
1844    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
1845        self.text.wait_for_version(version)
1846    }
1847
1848    /// Forces all futures returned by [`Buffer::wait_for_version`], [`Buffer::wait_for_edits`], or
1849    /// [`Buffer::wait_for_version`] to resolve with an error.
1850    pub fn give_up_waiting(&mut self) {
1851        self.text.give_up_waiting();
1852    }
1853
1854    /// Stores a set of selections that should be broadcasted to all of the buffer's replicas.
1855    pub fn set_active_selections(
1856        &mut self,
1857        selections: Arc<[Selection<Anchor>]>,
1858        line_mode: bool,
1859        cursor_shape: CursorShape,
1860        cx: &mut ModelContext<Self>,
1861    ) {
1862        let lamport_timestamp = self.text.lamport_clock.tick();
1863        self.remote_selections.insert(
1864            self.text.replica_id(),
1865            SelectionSet {
1866                selections: selections.clone(),
1867                lamport_timestamp,
1868                line_mode,
1869                cursor_shape,
1870            },
1871        );
1872        self.send_operation(
1873            Operation::UpdateSelections {
1874                selections,
1875                line_mode,
1876                lamport_timestamp,
1877                cursor_shape,
1878            },
1879            true,
1880            cx,
1881        );
1882        self.non_text_state_update_count += 1;
1883        cx.notify();
1884    }
1885
1886    /// Clears the selections, so that other replicas of the buffer do not see any selections for
1887    /// this replica.
1888    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1889        if self
1890            .remote_selections
1891            .get(&self.text.replica_id())
1892            .map_or(true, |set| !set.selections.is_empty())
1893        {
1894            self.set_active_selections(Arc::default(), false, Default::default(), cx);
1895        }
1896    }
1897
1898    /// Replaces the buffer's entire text.
1899    pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Lamport>
1900    where
1901        T: Into<Arc<str>>,
1902    {
1903        self.autoindent_requests.clear();
1904        self.edit([(0..self.len(), text)], None, cx)
1905    }
1906
1907    /// Applies the given edits to the buffer. Each edit is specified as a range of text to
1908    /// delete, and a string of text to insert at that location.
1909    ///
1910    /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
1911    /// request for the edited ranges, which will be processed when the buffer finishes
1912    /// parsing.
1913    ///
1914    /// Parsing takes place at the end of a transaction, and may compute synchronously
1915    /// or asynchronously, depending on the changes.
1916    pub fn edit<I, S, T>(
1917        &mut self,
1918        edits_iter: I,
1919        autoindent_mode: Option<AutoindentMode>,
1920        cx: &mut ModelContext<Self>,
1921    ) -> Option<clock::Lamport>
1922    where
1923        I: IntoIterator<Item = (Range<S>, T)>,
1924        S: ToOffset,
1925        T: Into<Arc<str>>,
1926    {
1927        // Skip invalid edits and coalesce contiguous ones.
1928        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1929        for (range, new_text) in edits_iter {
1930            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1931            if range.start > range.end {
1932                mem::swap(&mut range.start, &mut range.end);
1933            }
1934            let new_text = new_text.into();
1935            if !new_text.is_empty() || !range.is_empty() {
1936                if let Some((prev_range, prev_text)) = edits.last_mut() {
1937                    if prev_range.end >= range.start {
1938                        prev_range.end = cmp::max(prev_range.end, range.end);
1939                        *prev_text = format!("{prev_text}{new_text}").into();
1940                    } else {
1941                        edits.push((range, new_text));
1942                    }
1943                } else {
1944                    edits.push((range, new_text));
1945                }
1946            }
1947        }
1948        if edits.is_empty() {
1949            return None;
1950        }
1951
1952        self.start_transaction();
1953        self.pending_autoindent.take();
1954        let autoindent_request = autoindent_mode
1955            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
1956
1957        let edit_operation = self.text.edit(edits.iter().cloned());
1958        let edit_id = edit_operation.timestamp();
1959
1960        if let Some((before_edit, mode)) = autoindent_request {
1961            let mut delta = 0isize;
1962            let entries = edits
1963                .into_iter()
1964                .enumerate()
1965                .zip(&edit_operation.as_edit().unwrap().new_text)
1966                .map(|((ix, (range, _)), new_text)| {
1967                    let new_text_length = new_text.len();
1968                    let old_start = range.start.to_point(&before_edit);
1969                    let new_start = (delta + range.start as isize) as usize;
1970                    let range_len = range.end - range.start;
1971                    delta += new_text_length as isize - range_len as isize;
1972
1973                    // Decide what range of the insertion to auto-indent, and whether
1974                    // the first line of the insertion should be considered a newly-inserted line
1975                    // or an edit to an existing line.
1976                    let mut range_of_insertion_to_indent = 0..new_text_length;
1977                    let mut first_line_is_new = true;
1978
1979                    let old_line_start = before_edit.indent_size_for_line(old_start.row).len;
1980                    let old_line_end = before_edit.line_len(old_start.row);
1981
1982                    if old_start.column > old_line_start {
1983                        first_line_is_new = false;
1984                    }
1985
1986                    if !new_text.contains('\n')
1987                        && (old_start.column + (range_len as u32) < old_line_end
1988                            || old_line_end == old_line_start)
1989                    {
1990                        first_line_is_new = false;
1991                    }
1992
1993                    // When inserting text starting with a newline, avoid auto-indenting the
1994                    // previous line.
1995                    if new_text.starts_with('\n') {
1996                        range_of_insertion_to_indent.start += 1;
1997                        first_line_is_new = true;
1998                    }
1999
2000                    let mut original_indent_column = None;
2001                    if let AutoindentMode::Block {
2002                        original_indent_columns,
2003                    } = &mode
2004                    {
2005                        original_indent_column =
2006                            Some(original_indent_columns.get(ix).copied().unwrap_or_else(|| {
2007                                indent_size_for_text(
2008                                    new_text[range_of_insertion_to_indent.clone()].chars(),
2009                                )
2010                                .len
2011                            }));
2012
2013                        // Avoid auto-indenting the line after the edit.
2014                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
2015                            range_of_insertion_to_indent.end -= 1;
2016                        }
2017                    }
2018
2019                    AutoindentRequestEntry {
2020                        first_line_is_new,
2021                        original_indent_column,
2022                        indent_size: before_edit.language_indent_size_at(range.start, cx),
2023                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
2024                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
2025                    }
2026                })
2027                .collect();
2028
2029            self.autoindent_requests.push(Arc::new(AutoindentRequest {
2030                before_edit,
2031                entries,
2032                is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
2033            }));
2034        }
2035
2036        self.end_transaction(cx);
2037        self.send_operation(Operation::Buffer(edit_operation), true, cx);
2038        Some(edit_id)
2039    }
2040
2041    fn did_edit(
2042        &mut self,
2043        old_version: &clock::Global,
2044        was_dirty: bool,
2045        cx: &mut ModelContext<Self>,
2046    ) {
2047        if self.edits_since::<usize>(old_version).next().is_none() {
2048            return;
2049        }
2050
2051        self.reparse(cx);
2052
2053        cx.emit(BufferEvent::Edited);
2054        if was_dirty != self.is_dirty() {
2055            cx.emit(BufferEvent::DirtyChanged);
2056        }
2057        cx.notify();
2058    }
2059
2060    // Inserts newlines at the given position to create an empty line, returning the start of the new line.
2061    // You can also request the insertion of empty lines above and below the line starting at the returned point.
2062    pub fn insert_empty_line(
2063        &mut self,
2064        position: impl ToPoint,
2065        space_above: bool,
2066        space_below: bool,
2067        cx: &mut ModelContext<Self>,
2068    ) -> Point {
2069        let mut position = position.to_point(self);
2070
2071        self.start_transaction();
2072
2073        self.edit(
2074            [(position..position, "\n")],
2075            Some(AutoindentMode::EachLine),
2076            cx,
2077        );
2078
2079        if position.column > 0 {
2080            position += Point::new(1, 0);
2081        }
2082
2083        if !self.is_line_blank(position.row) {
2084            self.edit(
2085                [(position..position, "\n")],
2086                Some(AutoindentMode::EachLine),
2087                cx,
2088            );
2089        }
2090
2091        if space_above && position.row > 0 && !self.is_line_blank(position.row - 1) {
2092            self.edit(
2093                [(position..position, "\n")],
2094                Some(AutoindentMode::EachLine),
2095                cx,
2096            );
2097            position.row += 1;
2098        }
2099
2100        if space_below
2101            && (position.row == self.max_point().row || !self.is_line_blank(position.row + 1))
2102        {
2103            self.edit(
2104                [(position..position, "\n")],
2105                Some(AutoindentMode::EachLine),
2106                cx,
2107            );
2108        }
2109
2110        self.end_transaction(cx);
2111
2112        position
2113    }
2114
2115    /// Applies the given remote operations to the buffer.
2116    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
2117        &mut self,
2118        ops: I,
2119        cx: &mut ModelContext<Self>,
2120    ) {
2121        self.pending_autoindent.take();
2122        let was_dirty = self.is_dirty();
2123        let old_version = self.version.clone();
2124        let mut deferred_ops = Vec::new();
2125        let buffer_ops = ops
2126            .into_iter()
2127            .filter_map(|op| match op {
2128                Operation::Buffer(op) => Some(op),
2129                _ => {
2130                    if self.can_apply_op(&op) {
2131                        self.apply_op(op, cx);
2132                    } else {
2133                        deferred_ops.push(op);
2134                    }
2135                    None
2136                }
2137            })
2138            .collect::<Vec<_>>();
2139        for operation in buffer_ops.iter() {
2140            self.send_operation(Operation::Buffer(operation.clone()), false, cx);
2141        }
2142        self.text.apply_ops(buffer_ops);
2143        self.deferred_ops.insert(deferred_ops);
2144        self.flush_deferred_ops(cx);
2145        self.did_edit(&old_version, was_dirty, cx);
2146        // Notify independently of whether the buffer was edited as the operations could include a
2147        // selection update.
2148        cx.notify();
2149    }
2150
2151    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
2152        let mut deferred_ops = Vec::new();
2153        for op in self.deferred_ops.drain().iter().cloned() {
2154            if self.can_apply_op(&op) {
2155                self.apply_op(op, cx);
2156            } else {
2157                deferred_ops.push(op);
2158            }
2159        }
2160        self.deferred_ops.insert(deferred_ops);
2161    }
2162
2163    pub fn has_deferred_ops(&self) -> bool {
2164        !self.deferred_ops.is_empty() || self.text.has_deferred_ops()
2165    }
2166
2167    fn can_apply_op(&self, operation: &Operation) -> bool {
2168        match operation {
2169            Operation::Buffer(_) => {
2170                unreachable!("buffer operations should never be applied at this layer")
2171            }
2172            Operation::UpdateDiagnostics {
2173                diagnostics: diagnostic_set,
2174                ..
2175            } => diagnostic_set.iter().all(|diagnostic| {
2176                self.text.can_resolve(&diagnostic.range.start)
2177                    && self.text.can_resolve(&diagnostic.range.end)
2178            }),
2179            Operation::UpdateSelections { selections, .. } => selections
2180                .iter()
2181                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
2182            Operation::UpdateCompletionTriggers { .. } => true,
2183        }
2184    }
2185
2186    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
2187        match operation {
2188            Operation::Buffer(_) => {
2189                unreachable!("buffer operations should never be applied at this layer")
2190            }
2191            Operation::UpdateDiagnostics {
2192                server_id,
2193                diagnostics: diagnostic_set,
2194                lamport_timestamp,
2195            } => {
2196                let snapshot = self.snapshot();
2197                self.apply_diagnostic_update(
2198                    server_id,
2199                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
2200                    lamport_timestamp,
2201                    cx,
2202                );
2203            }
2204            Operation::UpdateSelections {
2205                selections,
2206                lamport_timestamp,
2207                line_mode,
2208                cursor_shape,
2209            } => {
2210                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
2211                    if set.lamport_timestamp > lamport_timestamp {
2212                        return;
2213                    }
2214                }
2215
2216                self.remote_selections.insert(
2217                    lamport_timestamp.replica_id,
2218                    SelectionSet {
2219                        selections,
2220                        lamport_timestamp,
2221                        line_mode,
2222                        cursor_shape,
2223                    },
2224                );
2225                self.text.lamport_clock.observe(lamport_timestamp);
2226                self.non_text_state_update_count += 1;
2227            }
2228            Operation::UpdateCompletionTriggers {
2229                triggers,
2230                lamport_timestamp,
2231            } => {
2232                self.completion_triggers = triggers;
2233                self.text.lamport_clock.observe(lamport_timestamp);
2234            }
2235        }
2236    }
2237
2238    fn apply_diagnostic_update(
2239        &mut self,
2240        server_id: LanguageServerId,
2241        diagnostics: DiagnosticSet,
2242        lamport_timestamp: clock::Lamport,
2243        cx: &mut ModelContext<Self>,
2244    ) {
2245        if lamport_timestamp > self.diagnostics_timestamp {
2246            let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
2247            if diagnostics.is_empty() {
2248                if let Ok(ix) = ix {
2249                    self.diagnostics.remove(ix);
2250                }
2251            } else {
2252                match ix {
2253                    Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
2254                    Ok(ix) => self.diagnostics[ix].1 = diagnostics,
2255                };
2256            }
2257            self.diagnostics_timestamp = lamport_timestamp;
2258            self.non_text_state_update_count += 1;
2259            self.text.lamport_clock.observe(lamport_timestamp);
2260            cx.notify();
2261            cx.emit(BufferEvent::DiagnosticsUpdated);
2262        }
2263    }
2264
2265    fn send_operation(&self, operation: Operation, is_local: bool, cx: &mut ModelContext<Self>) {
2266        cx.emit(BufferEvent::Operation {
2267            operation,
2268            is_local,
2269        });
2270    }
2271
2272    /// Removes the selections for a given peer.
2273    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
2274        self.remote_selections.remove(&replica_id);
2275        cx.notify();
2276    }
2277
2278    /// Undoes the most recent transaction.
2279    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
2280        let was_dirty = self.is_dirty();
2281        let old_version = self.version.clone();
2282
2283        if let Some((transaction_id, operation)) = self.text.undo() {
2284            self.send_operation(Operation::Buffer(operation), true, cx);
2285            self.did_edit(&old_version, was_dirty, cx);
2286            Some(transaction_id)
2287        } else {
2288            None
2289        }
2290    }
2291
2292    /// Manually undoes a specific transaction in the buffer's undo history.
2293    pub fn undo_transaction(
2294        &mut self,
2295        transaction_id: TransactionId,
2296        cx: &mut ModelContext<Self>,
2297    ) -> bool {
2298        let was_dirty = self.is_dirty();
2299        let old_version = self.version.clone();
2300        if let Some(operation) = self.text.undo_transaction(transaction_id) {
2301            self.send_operation(Operation::Buffer(operation), true, cx);
2302            self.did_edit(&old_version, was_dirty, cx);
2303            true
2304        } else {
2305            false
2306        }
2307    }
2308
2309    /// Manually undoes all changes after a given transaction in the buffer's undo history.
2310    pub fn undo_to_transaction(
2311        &mut self,
2312        transaction_id: TransactionId,
2313        cx: &mut ModelContext<Self>,
2314    ) -> bool {
2315        let was_dirty = self.is_dirty();
2316        let old_version = self.version.clone();
2317
2318        let operations = self.text.undo_to_transaction(transaction_id);
2319        let undone = !operations.is_empty();
2320        for operation in operations {
2321            self.send_operation(Operation::Buffer(operation), true, cx);
2322        }
2323        if undone {
2324            self.did_edit(&old_version, was_dirty, cx)
2325        }
2326        undone
2327    }
2328
2329    pub fn undo_operations(
2330        &mut self,
2331        counts: HashMap<Lamport, u32>,
2332        cx: &mut ModelContext<Buffer>,
2333    ) {
2334        let was_dirty = self.is_dirty();
2335        let operation = self.text.undo_operations(counts);
2336        let old_version = self.version.clone();
2337        self.send_operation(Operation::Buffer(operation), true, cx);
2338        self.did_edit(&old_version, was_dirty, cx);
2339    }
2340
2341    /// Manually redoes a specific transaction in the buffer's redo history.
2342    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
2343        let was_dirty = self.is_dirty();
2344        let old_version = self.version.clone();
2345
2346        if let Some((transaction_id, operation)) = self.text.redo() {
2347            self.send_operation(Operation::Buffer(operation), true, cx);
2348            self.did_edit(&old_version, was_dirty, cx);
2349            Some(transaction_id)
2350        } else {
2351            None
2352        }
2353    }
2354
2355    /// Manually undoes all changes until a given transaction in the buffer's redo history.
2356    pub fn redo_to_transaction(
2357        &mut self,
2358        transaction_id: TransactionId,
2359        cx: &mut ModelContext<Self>,
2360    ) -> bool {
2361        let was_dirty = self.is_dirty();
2362        let old_version = self.version.clone();
2363
2364        let operations = self.text.redo_to_transaction(transaction_id);
2365        let redone = !operations.is_empty();
2366        for operation in operations {
2367            self.send_operation(Operation::Buffer(operation), true, cx);
2368        }
2369        if redone {
2370            self.did_edit(&old_version, was_dirty, cx)
2371        }
2372        redone
2373    }
2374
2375    /// Override current completion triggers with the user-provided completion triggers.
2376    pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
2377        self.completion_triggers.clone_from(&triggers);
2378        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2379        self.send_operation(
2380            Operation::UpdateCompletionTriggers {
2381                triggers,
2382                lamport_timestamp: self.completion_triggers_timestamp,
2383            },
2384            true,
2385            cx,
2386        );
2387        cx.notify();
2388    }
2389
2390    /// Returns a list of strings which trigger a completion menu for this language.
2391    /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2392    pub fn completion_triggers(&self) -> &[String] {
2393        &self.completion_triggers
2394    }
2395
2396    /// Call this directly after performing edits to prevent the preview tab
2397    /// from being dismissed by those edits. It causes `should_dismiss_preview`
2398    /// to return false until there are additional edits.
2399    pub fn refresh_preview(&mut self) {
2400        self.preview_version = self.version.clone();
2401    }
2402
2403    /// Whether we should preserve the preview status of a tab containing this buffer.
2404    pub fn preserve_preview(&self) -> bool {
2405        !self.has_edits_since(&self.preview_version)
2406    }
2407}
2408
2409#[doc(hidden)]
2410#[cfg(any(test, feature = "test-support"))]
2411impl Buffer {
2412    pub fn edit_via_marked_text(
2413        &mut self,
2414        marked_string: &str,
2415        autoindent_mode: Option<AutoindentMode>,
2416        cx: &mut ModelContext<Self>,
2417    ) {
2418        let edits = self.edits_for_marked_text(marked_string);
2419        self.edit(edits, autoindent_mode, cx);
2420    }
2421
2422    pub fn set_group_interval(&mut self, group_interval: Duration) {
2423        self.text.set_group_interval(group_interval);
2424    }
2425
2426    pub fn randomly_edit<T>(
2427        &mut self,
2428        rng: &mut T,
2429        old_range_count: usize,
2430        cx: &mut ModelContext<Self>,
2431    ) where
2432        T: rand::Rng,
2433    {
2434        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2435        let mut last_end = None;
2436        for _ in 0..old_range_count {
2437            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2438                break;
2439            }
2440
2441            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2442            let mut range = self.random_byte_range(new_start, rng);
2443            if rng.gen_bool(0.2) {
2444                mem::swap(&mut range.start, &mut range.end);
2445            }
2446            last_end = Some(range.end);
2447
2448            let new_text_len = rng.gen_range(0..10);
2449            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2450
2451            edits.push((range, new_text));
2452        }
2453        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2454        self.edit(edits, None, cx);
2455    }
2456
2457    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
2458        let was_dirty = self.is_dirty();
2459        let old_version = self.version.clone();
2460
2461        let ops = self.text.randomly_undo_redo(rng);
2462        if !ops.is_empty() {
2463            for op in ops {
2464                self.send_operation(Operation::Buffer(op), true, cx);
2465                self.did_edit(&old_version, was_dirty, cx);
2466            }
2467        }
2468    }
2469}
2470
2471impl EventEmitter<BufferEvent> for Buffer {}
2472
2473impl Deref for Buffer {
2474    type Target = TextBuffer;
2475
2476    fn deref(&self) -> &Self::Target {
2477        &self.text
2478    }
2479}
2480
2481impl BufferSnapshot {
2482    /// Returns [`IndentSize`] for a given line that respects user settings and /// language preferences.
2483    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2484        indent_size_for_line(self, row)
2485    }
2486    /// Returns [`IndentSize`] for a given position that respects user settings
2487    /// and language preferences.
2488    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &AppContext) -> IndentSize {
2489        let settings = language_settings(
2490            self.language_at(position).map(|l| l.name()),
2491            self.file(),
2492            cx,
2493        );
2494        if settings.hard_tabs {
2495            IndentSize::tab()
2496        } else {
2497            IndentSize::spaces(settings.tab_size.get())
2498        }
2499    }
2500
2501    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2502    /// is passed in as `single_indent_size`.
2503    pub fn suggested_indents(
2504        &self,
2505        rows: impl Iterator<Item = u32>,
2506        single_indent_size: IndentSize,
2507    ) -> BTreeMap<u32, IndentSize> {
2508        let mut result = BTreeMap::new();
2509
2510        for row_range in contiguous_ranges(rows, 10) {
2511            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2512                Some(suggestions) => suggestions,
2513                _ => break,
2514            };
2515
2516            for (row, suggestion) in row_range.zip(suggestions) {
2517                let indent_size = if let Some(suggestion) = suggestion {
2518                    result
2519                        .get(&suggestion.basis_row)
2520                        .copied()
2521                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2522                        .with_delta(suggestion.delta, single_indent_size)
2523                } else {
2524                    self.indent_size_for_line(row)
2525                };
2526
2527                result.insert(row, indent_size);
2528            }
2529        }
2530
2531        result
2532    }
2533
2534    fn suggest_autoindents(
2535        &self,
2536        row_range: Range<u32>,
2537    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2538        let config = &self.language.as_ref()?.config;
2539        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2540
2541        // Find the suggested indentation ranges based on the syntax tree.
2542        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2543        let end = Point::new(row_range.end, 0);
2544        let range = (start..end).to_offset(&self.text);
2545        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2546            Some(&grammar.indents_config.as_ref()?.query)
2547        });
2548        let indent_configs = matches
2549            .grammars()
2550            .iter()
2551            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2552            .collect::<Vec<_>>();
2553
2554        let mut indent_ranges = Vec::<Range<Point>>::new();
2555        let mut outdent_positions = Vec::<Point>::new();
2556        while let Some(mat) = matches.peek() {
2557            let mut start: Option<Point> = None;
2558            let mut end: Option<Point> = None;
2559
2560            let config = &indent_configs[mat.grammar_index];
2561            for capture in mat.captures {
2562                if capture.index == config.indent_capture_ix {
2563                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2564                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2565                } else if Some(capture.index) == config.start_capture_ix {
2566                    start = Some(Point::from_ts_point(capture.node.end_position()));
2567                } else if Some(capture.index) == config.end_capture_ix {
2568                    end = Some(Point::from_ts_point(capture.node.start_position()));
2569                } else if Some(capture.index) == config.outdent_capture_ix {
2570                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2571                }
2572            }
2573
2574            matches.advance();
2575            if let Some((start, end)) = start.zip(end) {
2576                if start.row == end.row {
2577                    continue;
2578                }
2579
2580                let range = start..end;
2581                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2582                    Err(ix) => indent_ranges.insert(ix, range),
2583                    Ok(ix) => {
2584                        let prev_range = &mut indent_ranges[ix];
2585                        prev_range.end = prev_range.end.max(range.end);
2586                    }
2587                }
2588            }
2589        }
2590
2591        let mut error_ranges = Vec::<Range<Point>>::new();
2592        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2593            Some(&grammar.error_query)
2594        });
2595        while let Some(mat) = matches.peek() {
2596            let node = mat.captures[0].node;
2597            let start = Point::from_ts_point(node.start_position());
2598            let end = Point::from_ts_point(node.end_position());
2599            let range = start..end;
2600            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2601                Ok(ix) | Err(ix) => ix,
2602            };
2603            let mut end_ix = ix;
2604            while let Some(existing_range) = error_ranges.get(end_ix) {
2605                if existing_range.end < end {
2606                    end_ix += 1;
2607                } else {
2608                    break;
2609                }
2610            }
2611            error_ranges.splice(ix..end_ix, [range]);
2612            matches.advance();
2613        }
2614
2615        outdent_positions.sort();
2616        for outdent_position in outdent_positions {
2617            // find the innermost indent range containing this outdent_position
2618            // set its end to the outdent position
2619            if let Some(range_to_truncate) = indent_ranges
2620                .iter_mut()
2621                .filter(|indent_range| indent_range.contains(&outdent_position))
2622                .last()
2623            {
2624                range_to_truncate.end = outdent_position;
2625            }
2626        }
2627
2628        // Find the suggested indentation increases and decreased based on regexes.
2629        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2630        self.for_each_line(
2631            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2632                ..Point::new(row_range.end, 0),
2633            |row, line| {
2634                if config
2635                    .decrease_indent_pattern
2636                    .as_ref()
2637                    .map_or(false, |regex| regex.is_match(line))
2638                {
2639                    indent_change_rows.push((row, Ordering::Less));
2640                }
2641                if config
2642                    .increase_indent_pattern
2643                    .as_ref()
2644                    .map_or(false, |regex| regex.is_match(line))
2645                {
2646                    indent_change_rows.push((row + 1, Ordering::Greater));
2647                }
2648            },
2649        );
2650
2651        let mut indent_changes = indent_change_rows.into_iter().peekable();
2652        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2653            prev_non_blank_row.unwrap_or(0)
2654        } else {
2655            row_range.start.saturating_sub(1)
2656        };
2657        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2658        Some(row_range.map(move |row| {
2659            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2660
2661            let mut indent_from_prev_row = false;
2662            let mut outdent_from_prev_row = false;
2663            let mut outdent_to_row = u32::MAX;
2664
2665            while let Some((indent_row, delta)) = indent_changes.peek() {
2666                match indent_row.cmp(&row) {
2667                    Ordering::Equal => match delta {
2668                        Ordering::Less => outdent_from_prev_row = true,
2669                        Ordering::Greater => indent_from_prev_row = true,
2670                        _ => {}
2671                    },
2672
2673                    Ordering::Greater => break,
2674                    Ordering::Less => {}
2675                }
2676
2677                indent_changes.next();
2678            }
2679
2680            for range in &indent_ranges {
2681                if range.start.row >= row {
2682                    break;
2683                }
2684                if range.start.row == prev_row && range.end > row_start {
2685                    indent_from_prev_row = true;
2686                }
2687                if range.end > prev_row_start && range.end <= row_start {
2688                    outdent_to_row = outdent_to_row.min(range.start.row);
2689                }
2690            }
2691
2692            let within_error = error_ranges
2693                .iter()
2694                .any(|e| e.start.row < row && e.end > row_start);
2695
2696            let suggestion = if outdent_to_row == prev_row
2697                || (outdent_from_prev_row && indent_from_prev_row)
2698            {
2699                Some(IndentSuggestion {
2700                    basis_row: prev_row,
2701                    delta: Ordering::Equal,
2702                    within_error,
2703                })
2704            } else if indent_from_prev_row {
2705                Some(IndentSuggestion {
2706                    basis_row: prev_row,
2707                    delta: Ordering::Greater,
2708                    within_error,
2709                })
2710            } else if outdent_to_row < prev_row {
2711                Some(IndentSuggestion {
2712                    basis_row: outdent_to_row,
2713                    delta: Ordering::Equal,
2714                    within_error,
2715                })
2716            } else if outdent_from_prev_row {
2717                Some(IndentSuggestion {
2718                    basis_row: prev_row,
2719                    delta: Ordering::Less,
2720                    within_error,
2721                })
2722            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
2723            {
2724                Some(IndentSuggestion {
2725                    basis_row: prev_row,
2726                    delta: Ordering::Equal,
2727                    within_error,
2728                })
2729            } else {
2730                None
2731            };
2732
2733            prev_row = row;
2734            prev_row_start = row_start;
2735            suggestion
2736        }))
2737    }
2738
2739    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2740        while row > 0 {
2741            row -= 1;
2742            if !self.is_line_blank(row) {
2743                return Some(row);
2744            }
2745        }
2746        None
2747    }
2748
2749    fn get_highlights(&self, range: Range<usize>) -> (SyntaxMapCaptures, Vec<HighlightMap>) {
2750        let captures = self.syntax.captures(range, &self.text, |grammar| {
2751            grammar.highlights_query.as_ref()
2752        });
2753        let highlight_maps = captures
2754            .grammars()
2755            .iter()
2756            .map(|grammar| grammar.highlight_map())
2757            .collect();
2758        (captures, highlight_maps)
2759    }
2760
2761    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
2762    /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
2763    /// returned in chunks where each chunk has a single syntax highlighting style and
2764    /// diagnostic status.
2765    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
2766        let range = range.start.to_offset(self)..range.end.to_offset(self);
2767
2768        let mut syntax = None;
2769        if language_aware {
2770            syntax = Some(self.get_highlights(range.clone()));
2771        }
2772        // We want to look at diagnostic spans only when iterating over language-annotated chunks.
2773        let diagnostics = language_aware;
2774        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostics, Some(self))
2775    }
2776
2777    /// Invokes the given callback for each line of text in the given range of the buffer.
2778    /// Uses callback to avoid allocating a string for each line.
2779    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
2780        let mut line = String::new();
2781        let mut row = range.start.row;
2782        for chunk in self
2783            .as_rope()
2784            .chunks_in_range(range.to_offset(self))
2785            .chain(["\n"])
2786        {
2787            for (newline_ix, text) in chunk.split('\n').enumerate() {
2788                if newline_ix > 0 {
2789                    callback(row, &line);
2790                    row += 1;
2791                    line.clear();
2792                }
2793                line.push_str(text);
2794            }
2795        }
2796    }
2797
2798    /// Iterates over every [`SyntaxLayer`] in the buffer.
2799    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
2800        self.syntax
2801            .layers_for_range(0..self.len(), &self.text, true)
2802    }
2803
2804    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
2805        let offset = position.to_offset(self);
2806        self.syntax
2807            .layers_for_range(offset..offset, &self.text, false)
2808            .filter(|l| l.node().end_byte() > offset)
2809            .last()
2810    }
2811
2812    /// Returns the main [`Language`].
2813    pub fn language(&self) -> Option<&Arc<Language>> {
2814        self.language.as_ref()
2815    }
2816
2817    /// Returns the [`Language`] at the given location.
2818    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
2819        self.syntax_layer_at(position)
2820            .map(|info| info.language)
2821            .or(self.language.as_ref())
2822    }
2823
2824    /// Returns the settings for the language at the given location.
2825    pub fn settings_at<'a, D: ToOffset>(
2826        &'a self,
2827        position: D,
2828        cx: &'a AppContext,
2829    ) -> Cow<'a, LanguageSettings> {
2830        language_settings(
2831            self.language_at(position).map(|l| l.name()),
2832            self.file.as_ref(),
2833            cx,
2834        )
2835    }
2836
2837    pub fn char_classifier_at<T: ToOffset>(&self, point: T) -> CharClassifier {
2838        CharClassifier::new(self.language_scope_at(point))
2839    }
2840
2841    /// Returns the [`LanguageScope`] at the given location.
2842    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
2843        let offset = position.to_offset(self);
2844        let mut scope = None;
2845        let mut smallest_range: Option<Range<usize>> = None;
2846
2847        // Use the layer that has the smallest node intersecting the given point.
2848        for layer in self
2849            .syntax
2850            .layers_for_range(offset..offset, &self.text, false)
2851        {
2852            let mut cursor = layer.node().walk();
2853
2854            let mut range = None;
2855            loop {
2856                let child_range = cursor.node().byte_range();
2857                if !child_range.to_inclusive().contains(&offset) {
2858                    break;
2859                }
2860
2861                range = Some(child_range);
2862                if cursor.goto_first_child_for_byte(offset).is_none() {
2863                    break;
2864                }
2865            }
2866
2867            if let Some(range) = range {
2868                if smallest_range
2869                    .as_ref()
2870                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
2871                {
2872                    smallest_range = Some(range);
2873                    scope = Some(LanguageScope {
2874                        language: layer.language.clone(),
2875                        override_id: layer.override_id(offset, &self.text),
2876                    });
2877                }
2878            }
2879        }
2880
2881        scope.or_else(|| {
2882            self.language.clone().map(|language| LanguageScope {
2883                language,
2884                override_id: None,
2885            })
2886        })
2887    }
2888
2889    /// Returns a tuple of the range and character kind of the word
2890    /// surrounding the given position.
2891    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2892        let mut start = start.to_offset(self);
2893        let mut end = start;
2894        let mut next_chars = self.chars_at(start).peekable();
2895        let mut prev_chars = self.reversed_chars_at(start).peekable();
2896
2897        let classifier = self.char_classifier_at(start);
2898        let word_kind = cmp::max(
2899            prev_chars.peek().copied().map(|c| classifier.kind(c)),
2900            next_chars.peek().copied().map(|c| classifier.kind(c)),
2901        );
2902
2903        for ch in prev_chars {
2904            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
2905                start -= ch.len_utf8();
2906            } else {
2907                break;
2908            }
2909        }
2910
2911        for ch in next_chars {
2912            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
2913                end += ch.len_utf8();
2914            } else {
2915                break;
2916            }
2917        }
2918
2919        (start..end, word_kind)
2920    }
2921
2922    /// Returns the range for the closes syntax node enclosing the given range.
2923    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2924        let range = range.start.to_offset(self)..range.end.to_offset(self);
2925        let mut result: Option<Range<usize>> = None;
2926        'outer: for layer in self
2927            .syntax
2928            .layers_for_range(range.clone(), &self.text, true)
2929        {
2930            let mut cursor = layer.node().walk();
2931
2932            // Descend to the first leaf that touches the start of the range,
2933            // and if the range is non-empty, extends beyond the start.
2934            while cursor.goto_first_child_for_byte(range.start).is_some() {
2935                if !range.is_empty() && cursor.node().end_byte() == range.start {
2936                    cursor.goto_next_sibling();
2937                }
2938            }
2939
2940            // Ascend to the smallest ancestor that strictly contains the range.
2941            loop {
2942                let node_range = cursor.node().byte_range();
2943                if node_range.start <= range.start
2944                    && node_range.end >= range.end
2945                    && node_range.len() > range.len()
2946                {
2947                    break;
2948                }
2949                if !cursor.goto_parent() {
2950                    continue 'outer;
2951                }
2952            }
2953
2954            let left_node = cursor.node();
2955            let mut layer_result = left_node.byte_range();
2956
2957            // For an empty range, try to find another node immediately to the right of the range.
2958            if left_node.end_byte() == range.start {
2959                let mut right_node = None;
2960                while !cursor.goto_next_sibling() {
2961                    if !cursor.goto_parent() {
2962                        break;
2963                    }
2964                }
2965
2966                while cursor.node().start_byte() == range.start {
2967                    right_node = Some(cursor.node());
2968                    if !cursor.goto_first_child() {
2969                        break;
2970                    }
2971                }
2972
2973                // If there is a candidate node on both sides of the (empty) range, then
2974                // decide between the two by favoring a named node over an anonymous token.
2975                // If both nodes are the same in that regard, favor the right one.
2976                if let Some(right_node) = right_node {
2977                    if right_node.is_named() || !left_node.is_named() {
2978                        layer_result = right_node.byte_range();
2979                    }
2980                }
2981            }
2982
2983            if let Some(previous_result) = &result {
2984                if previous_result.len() < layer_result.len() {
2985                    continue;
2986                }
2987            }
2988            result = Some(layer_result);
2989        }
2990
2991        result
2992    }
2993
2994    /// Returns the outline for the buffer.
2995    ///
2996    /// This method allows passing an optional [`SyntaxTheme`] to
2997    /// syntax-highlight the returned symbols.
2998    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2999        self.outline_items_containing(0..self.len(), true, theme)
3000            .map(Outline::new)
3001    }
3002
3003    /// Returns all the symbols that contain the given position.
3004    ///
3005    /// This method allows passing an optional [`SyntaxTheme`] to
3006    /// syntax-highlight the returned symbols.
3007    pub fn symbols_containing<T: ToOffset>(
3008        &self,
3009        position: T,
3010        theme: Option<&SyntaxTheme>,
3011    ) -> Option<Vec<OutlineItem<Anchor>>> {
3012        let position = position.to_offset(self);
3013        let mut items = self.outline_items_containing(
3014            position.saturating_sub(1)..self.len().min(position + 1),
3015            false,
3016            theme,
3017        )?;
3018        let mut prev_depth = None;
3019        items.retain(|item| {
3020            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
3021            prev_depth = Some(item.depth);
3022            result
3023        });
3024        Some(items)
3025    }
3026
3027    pub fn outline_items_containing<T: ToOffset>(
3028        &self,
3029        range: Range<T>,
3030        include_extra_context: bool,
3031        theme: Option<&SyntaxTheme>,
3032    ) -> Option<Vec<OutlineItem<Anchor>>> {
3033        let range = range.to_offset(self);
3034        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3035            grammar.outline_config.as_ref().map(|c| &c.query)
3036        });
3037        let configs = matches
3038            .grammars()
3039            .iter()
3040            .map(|g| g.outline_config.as_ref().unwrap())
3041            .collect::<Vec<_>>();
3042
3043        let mut items = Vec::new();
3044        let mut annotation_row_ranges: Vec<Range<u32>> = Vec::new();
3045        while let Some(mat) = matches.peek() {
3046            let config = &configs[mat.grammar_index];
3047            if let Some(item) =
3048                self.next_outline_item(config, &mat, &range, include_extra_context, theme)
3049            {
3050                items.push(item);
3051            } else if let Some(capture) = mat
3052                .captures
3053                .iter()
3054                .find(|capture| Some(capture.index) == config.annotation_capture_ix)
3055            {
3056                let capture_range = capture.node.start_position()..capture.node.end_position();
3057                let mut capture_row_range =
3058                    capture_range.start.row as u32..capture_range.end.row as u32;
3059                if capture_range.end.row > capture_range.start.row && capture_range.end.column == 0
3060                {
3061                    capture_row_range.end -= 1;
3062                }
3063                if let Some(last_row_range) = annotation_row_ranges.last_mut() {
3064                    if last_row_range.end >= capture_row_range.start.saturating_sub(1) {
3065                        last_row_range.end = capture_row_range.end;
3066                    } else {
3067                        annotation_row_ranges.push(capture_row_range);
3068                    }
3069                } else {
3070                    annotation_row_ranges.push(capture_row_range);
3071                }
3072            }
3073            matches.advance();
3074        }
3075
3076        items.sort_by_key(|item| (item.range.start, Reverse(item.range.end)));
3077
3078        // Assign depths based on containment relationships and convert to anchors.
3079        let mut item_ends_stack = Vec::<Point>::new();
3080        let mut anchor_items = Vec::new();
3081        let mut annotation_row_ranges = annotation_row_ranges.into_iter().peekable();
3082        for item in items {
3083            while let Some(last_end) = item_ends_stack.last().copied() {
3084                if last_end < item.range.end {
3085                    item_ends_stack.pop();
3086                } else {
3087                    break;
3088                }
3089            }
3090
3091            let mut annotation_row_range = None;
3092            while let Some(next_annotation_row_range) = annotation_row_ranges.peek() {
3093                let row_preceding_item = item.range.start.row.saturating_sub(1);
3094                if next_annotation_row_range.end < row_preceding_item {
3095                    annotation_row_ranges.next();
3096                } else {
3097                    if next_annotation_row_range.end == row_preceding_item {
3098                        annotation_row_range = Some(next_annotation_row_range.clone());
3099                        annotation_row_ranges.next();
3100                    }
3101                    break;
3102                }
3103            }
3104
3105            anchor_items.push(OutlineItem {
3106                depth: item_ends_stack.len(),
3107                range: self.anchor_after(item.range.start)..self.anchor_before(item.range.end),
3108                text: item.text,
3109                highlight_ranges: item.highlight_ranges,
3110                name_ranges: item.name_ranges,
3111                body_range: item.body_range.map(|body_range| {
3112                    self.anchor_after(body_range.start)..self.anchor_before(body_range.end)
3113                }),
3114                annotation_range: annotation_row_range.map(|annotation_range| {
3115                    self.anchor_after(Point::new(annotation_range.start, 0))
3116                        ..self.anchor_before(Point::new(
3117                            annotation_range.end,
3118                            self.line_len(annotation_range.end),
3119                        ))
3120                }),
3121            });
3122            item_ends_stack.push(item.range.end);
3123        }
3124
3125        Some(anchor_items)
3126    }
3127
3128    fn next_outline_item(
3129        &self,
3130        config: &OutlineConfig,
3131        mat: &SyntaxMapMatch,
3132        range: &Range<usize>,
3133        include_extra_context: bool,
3134        theme: Option<&SyntaxTheme>,
3135    ) -> Option<OutlineItem<Point>> {
3136        let item_node = mat.captures.iter().find_map(|cap| {
3137            if cap.index == config.item_capture_ix {
3138                Some(cap.node)
3139            } else {
3140                None
3141            }
3142        })?;
3143
3144        let item_byte_range = item_node.byte_range();
3145        if item_byte_range.end < range.start || item_byte_range.start > range.end {
3146            return None;
3147        }
3148        let item_point_range = Point::from_ts_point(item_node.start_position())
3149            ..Point::from_ts_point(item_node.end_position());
3150
3151        let mut open_point = None;
3152        let mut close_point = None;
3153        let mut buffer_ranges = Vec::new();
3154        for capture in mat.captures {
3155            let node_is_name;
3156            if capture.index == config.name_capture_ix {
3157                node_is_name = true;
3158            } else if Some(capture.index) == config.context_capture_ix
3159                || (Some(capture.index) == config.extra_context_capture_ix && include_extra_context)
3160            {
3161                node_is_name = false;
3162            } else {
3163                if Some(capture.index) == config.open_capture_ix {
3164                    open_point = Some(Point::from_ts_point(capture.node.end_position()));
3165                } else if Some(capture.index) == config.close_capture_ix {
3166                    close_point = Some(Point::from_ts_point(capture.node.start_position()));
3167                }
3168
3169                continue;
3170            }
3171
3172            let mut range = capture.node.start_byte()..capture.node.end_byte();
3173            let start = capture.node.start_position();
3174            if capture.node.end_position().row > start.row {
3175                range.end = range.start + self.line_len(start.row as u32) as usize - start.column;
3176            }
3177
3178            if !range.is_empty() {
3179                buffer_ranges.push((range, node_is_name));
3180            }
3181        }
3182        if buffer_ranges.is_empty() {
3183            return None;
3184        }
3185        let mut text = String::new();
3186        let mut highlight_ranges = Vec::new();
3187        let mut name_ranges = Vec::new();
3188        let mut chunks = self.chunks(
3189            buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
3190            true,
3191        );
3192        let mut last_buffer_range_end = 0;
3193        for (buffer_range, is_name) in buffer_ranges {
3194            if !text.is_empty() && buffer_range.start > last_buffer_range_end {
3195                text.push(' ');
3196            }
3197            last_buffer_range_end = buffer_range.end;
3198            if is_name {
3199                let mut start = text.len();
3200                let end = start + buffer_range.len();
3201
3202                // When multiple names are captured, then the matchable text
3203                // includes the whitespace in between the names.
3204                if !name_ranges.is_empty() {
3205                    start -= 1;
3206                }
3207
3208                name_ranges.push(start..end);
3209            }
3210
3211            let mut offset = buffer_range.start;
3212            chunks.seek(buffer_range.clone());
3213            for mut chunk in chunks.by_ref() {
3214                if chunk.text.len() > buffer_range.end - offset {
3215                    chunk.text = &chunk.text[0..(buffer_range.end - offset)];
3216                    offset = buffer_range.end;
3217                } else {
3218                    offset += chunk.text.len();
3219                }
3220                let style = chunk
3221                    .syntax_highlight_id
3222                    .zip(theme)
3223                    .and_then(|(highlight, theme)| highlight.style(theme));
3224                if let Some(style) = style {
3225                    let start = text.len();
3226                    let end = start + chunk.text.len();
3227                    highlight_ranges.push((start..end, style));
3228                }
3229                text.push_str(chunk.text);
3230                if offset >= buffer_range.end {
3231                    break;
3232                }
3233            }
3234        }
3235
3236        Some(OutlineItem {
3237            depth: 0, // We'll calculate the depth later
3238            range: item_point_range,
3239            text,
3240            highlight_ranges,
3241            name_ranges,
3242            body_range: open_point.zip(close_point).map(|(start, end)| start..end),
3243            annotation_range: None,
3244        })
3245    }
3246
3247    /// For each grammar in the language, runs the provided
3248    /// [`tree_sitter::Query`] against the given range.
3249    pub fn matches(
3250        &self,
3251        range: Range<usize>,
3252        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
3253    ) -> SyntaxMapMatches {
3254        self.syntax.matches(range, self, query)
3255    }
3256
3257    /// Returns bracket range pairs overlapping or adjacent to `range`
3258    pub fn bracket_ranges<T: ToOffset>(
3259        &self,
3260        range: Range<T>,
3261    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3262        // Find bracket pairs that *inclusively* contain the given range.
3263        let range = range.start.to_offset(self).saturating_sub(1)
3264            ..self.len().min(range.end.to_offset(self) + 1);
3265
3266        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3267            grammar.brackets_config.as_ref().map(|c| &c.query)
3268        });
3269        let configs = matches
3270            .grammars()
3271            .iter()
3272            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
3273            .collect::<Vec<_>>();
3274
3275        iter::from_fn(move || {
3276            while let Some(mat) = matches.peek() {
3277                let mut open = None;
3278                let mut close = None;
3279                let config = &configs[mat.grammar_index];
3280                for capture in mat.captures {
3281                    if capture.index == config.open_capture_ix {
3282                        open = Some(capture.node.byte_range());
3283                    } else if capture.index == config.close_capture_ix {
3284                        close = Some(capture.node.byte_range());
3285                    }
3286                }
3287
3288                matches.advance();
3289
3290                let Some((open, close)) = open.zip(close) else {
3291                    continue;
3292                };
3293
3294                let bracket_range = open.start..=close.end;
3295                if !bracket_range.overlaps(&range) {
3296                    continue;
3297                }
3298
3299                return Some((open, close));
3300            }
3301            None
3302        })
3303    }
3304
3305    /// Returns enclosing bracket ranges containing the given range
3306    pub fn enclosing_bracket_ranges<T: ToOffset>(
3307        &self,
3308        range: Range<T>,
3309    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3310        let range = range.start.to_offset(self)..range.end.to_offset(self);
3311
3312        self.bracket_ranges(range.clone())
3313            .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
3314    }
3315
3316    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3317    ///
3318    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3319    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3320        &self,
3321        range: Range<T>,
3322        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3323    ) -> Option<(Range<usize>, Range<usize>)> {
3324        let range = range.start.to_offset(self)..range.end.to_offset(self);
3325
3326        // Get the ranges of the innermost pair of brackets.
3327        let mut result: Option<(Range<usize>, Range<usize>)> = None;
3328
3329        for (open, close) in self.enclosing_bracket_ranges(range.clone()) {
3330            if let Some(range_filter) = range_filter {
3331                if !range_filter(open.clone(), close.clone()) {
3332                    continue;
3333                }
3334            }
3335
3336            let len = close.end - open.start;
3337
3338            if let Some((existing_open, existing_close)) = &result {
3339                let existing_len = existing_close.end - existing_open.start;
3340                if len > existing_len {
3341                    continue;
3342                }
3343            }
3344
3345            result = Some((open, close));
3346        }
3347
3348        result
3349    }
3350
3351    /// Returns anchor ranges for any matches of the redaction query.
3352    /// The buffer can be associated with multiple languages, and the redaction query associated with each
3353    /// will be run on the relevant section of the buffer.
3354    pub fn redacted_ranges<T: ToOffset>(
3355        &self,
3356        range: Range<T>,
3357    ) -> impl Iterator<Item = Range<usize>> + '_ {
3358        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3359        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3360            grammar
3361                .redactions_config
3362                .as_ref()
3363                .map(|config| &config.query)
3364        });
3365
3366        let configs = syntax_matches
3367            .grammars()
3368            .iter()
3369            .map(|grammar| grammar.redactions_config.as_ref())
3370            .collect::<Vec<_>>();
3371
3372        iter::from_fn(move || {
3373            let redacted_range = syntax_matches
3374                .peek()
3375                .and_then(|mat| {
3376                    configs[mat.grammar_index].and_then(|config| {
3377                        mat.captures
3378                            .iter()
3379                            .find(|capture| capture.index == config.redaction_capture_ix)
3380                    })
3381                })
3382                .map(|mat| mat.node.byte_range());
3383            syntax_matches.advance();
3384            redacted_range
3385        })
3386    }
3387
3388    pub fn injections_intersecting_range<T: ToOffset>(
3389        &self,
3390        range: Range<T>,
3391    ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3392        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3393
3394        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3395            grammar
3396                .injection_config
3397                .as_ref()
3398                .map(|config| &config.query)
3399        });
3400
3401        let configs = syntax_matches
3402            .grammars()
3403            .iter()
3404            .map(|grammar| grammar.injection_config.as_ref())
3405            .collect::<Vec<_>>();
3406
3407        iter::from_fn(move || {
3408            let ranges = syntax_matches.peek().and_then(|mat| {
3409                let config = &configs[mat.grammar_index]?;
3410                let content_capture_range = mat.captures.iter().find_map(|capture| {
3411                    if capture.index == config.content_capture_ix {
3412                        Some(capture.node.byte_range())
3413                    } else {
3414                        None
3415                    }
3416                })?;
3417                let language = self.language_at(content_capture_range.start)?;
3418                Some((content_capture_range, language))
3419            });
3420            syntax_matches.advance();
3421            ranges
3422        })
3423    }
3424
3425    pub fn runnable_ranges(
3426        &self,
3427        range: Range<Anchor>,
3428    ) -> impl Iterator<Item = RunnableRange> + '_ {
3429        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3430
3431        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3432            grammar.runnable_config.as_ref().map(|config| &config.query)
3433        });
3434
3435        let test_configs = syntax_matches
3436            .grammars()
3437            .iter()
3438            .map(|grammar| grammar.runnable_config.as_ref())
3439            .collect::<Vec<_>>();
3440
3441        iter::from_fn(move || loop {
3442            let mat = syntax_matches.peek()?;
3443
3444            let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3445                let mut run_range = None;
3446                let full_range = mat.captures.iter().fold(
3447                    Range {
3448                        start: usize::MAX,
3449                        end: 0,
3450                    },
3451                    |mut acc, next| {
3452                        let byte_range = next.node.byte_range();
3453                        if acc.start > byte_range.start {
3454                            acc.start = byte_range.start;
3455                        }
3456                        if acc.end < byte_range.end {
3457                            acc.end = byte_range.end;
3458                        }
3459                        acc
3460                    },
3461                );
3462                if full_range.start > full_range.end {
3463                    // We did not find a full spanning range of this match.
3464                    return None;
3465                }
3466                let extra_captures: SmallVec<[_; 1]> =
3467                    SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3468                        test_configs
3469                            .extra_captures
3470                            .get(capture.index as usize)
3471                            .cloned()
3472                            .and_then(|tag_name| match tag_name {
3473                                RunnableCapture::Named(name) => {
3474                                    Some((capture.node.byte_range(), name))
3475                                }
3476                                RunnableCapture::Run => {
3477                                    let _ = run_range.insert(capture.node.byte_range());
3478                                    None
3479                                }
3480                            })
3481                    }));
3482                let run_range = run_range?;
3483                let tags = test_configs
3484                    .query
3485                    .property_settings(mat.pattern_index)
3486                    .iter()
3487                    .filter_map(|property| {
3488                        if *property.key == *"tag" {
3489                            property
3490                                .value
3491                                .as_ref()
3492                                .map(|value| RunnableTag(value.to_string().into()))
3493                        } else {
3494                            None
3495                        }
3496                    })
3497                    .collect();
3498                let extra_captures = extra_captures
3499                    .into_iter()
3500                    .map(|(range, name)| {
3501                        (
3502                            name.to_string(),
3503                            self.text_for_range(range.clone()).collect::<String>(),
3504                        )
3505                    })
3506                    .collect();
3507                // All tags should have the same range.
3508                Some(RunnableRange {
3509                    run_range,
3510                    full_range,
3511                    runnable: Runnable {
3512                        tags,
3513                        language: mat.language,
3514                        buffer: self.remote_id(),
3515                    },
3516                    extra_captures,
3517                    buffer_id: self.remote_id(),
3518                })
3519            });
3520
3521            syntax_matches.advance();
3522            if test_range.is_some() {
3523                // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
3524                // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
3525                return test_range;
3526            }
3527        })
3528    }
3529
3530    pub fn indent_guides_in_range(
3531        &self,
3532        range: Range<Anchor>,
3533        ignore_disabled_for_language: bool,
3534        cx: &AppContext,
3535    ) -> Vec<IndentGuide> {
3536        let language_settings =
3537            language_settings(self.language().map(|l| l.name()), self.file.as_ref(), cx);
3538        let settings = language_settings.indent_guides;
3539        if !ignore_disabled_for_language && !settings.enabled {
3540            return Vec::new();
3541        }
3542        let tab_size = language_settings.tab_size.get() as u32;
3543
3544        let start_row = range.start.to_point(self).row;
3545        let end_row = range.end.to_point(self).row;
3546        let row_range = start_row..end_row + 1;
3547
3548        let mut row_indents = self.line_indents_in_row_range(row_range.clone());
3549
3550        let mut result_vec = Vec::new();
3551        let mut indent_stack = SmallVec::<[IndentGuide; 8]>::new();
3552
3553        while let Some((first_row, mut line_indent)) = row_indents.next() {
3554            let current_depth = indent_stack.len() as u32;
3555
3556            // When encountering empty, continue until found useful line indent
3557            // then add to the indent stack with the depth found
3558            let mut found_indent = false;
3559            let mut last_row = first_row;
3560            if line_indent.is_line_empty() {
3561                let mut trailing_row = end_row;
3562                while !found_indent {
3563                    let (target_row, new_line_indent) =
3564                        if let Some(display_row) = row_indents.next() {
3565                            display_row
3566                        } else {
3567                            // This means we reached the end of the given range and found empty lines at the end.
3568                            // We need to traverse further until we find a non-empty line to know if we need to add
3569                            // an indent guide for the last visible indent.
3570                            trailing_row += 1;
3571
3572                            const TRAILING_ROW_SEARCH_LIMIT: u32 = 25;
3573                            if trailing_row > self.max_point().row
3574                                || trailing_row > end_row + TRAILING_ROW_SEARCH_LIMIT
3575                            {
3576                                break;
3577                            }
3578                            let new_line_indent = self.line_indent_for_row(trailing_row);
3579                            (trailing_row, new_line_indent)
3580                        };
3581
3582                    if new_line_indent.is_line_empty() {
3583                        continue;
3584                    }
3585                    last_row = target_row.min(end_row);
3586                    line_indent = new_line_indent;
3587                    found_indent = true;
3588                    break;
3589                }
3590            } else {
3591                found_indent = true
3592            }
3593
3594            let depth = if found_indent {
3595                line_indent.len(tab_size) / tab_size
3596                    + ((line_indent.len(tab_size) % tab_size) > 0) as u32
3597            } else {
3598                current_depth
3599            };
3600
3601            match depth.cmp(&current_depth) {
3602                Ordering::Less => {
3603                    for _ in 0..(current_depth - depth) {
3604                        let mut indent = indent_stack.pop().unwrap();
3605                        if last_row != first_row {
3606                            // In this case, we landed on an empty row, had to seek forward,
3607                            // and discovered that the indent we where on is ending.
3608                            // This means that the last display row must
3609                            // be on line that ends this indent range, so we
3610                            // should display the range up to the first non-empty line
3611                            indent.end_row = first_row.saturating_sub(1);
3612                        }
3613
3614                        result_vec.push(indent)
3615                    }
3616                }
3617                Ordering::Greater => {
3618                    for next_depth in current_depth..depth {
3619                        indent_stack.push(IndentGuide {
3620                            buffer_id: self.remote_id(),
3621                            start_row: first_row,
3622                            end_row: last_row,
3623                            depth: next_depth,
3624                            tab_size,
3625                            settings,
3626                        });
3627                    }
3628                }
3629                _ => {}
3630            }
3631
3632            for indent in indent_stack.iter_mut() {
3633                indent.end_row = last_row;
3634            }
3635        }
3636
3637        result_vec.extend(indent_stack);
3638
3639        result_vec
3640    }
3641
3642    pub async fn enclosing_indent(
3643        &self,
3644        mut buffer_row: BufferRow,
3645    ) -> Option<(Range<BufferRow>, LineIndent)> {
3646        let max_row = self.max_point().row;
3647        if buffer_row >= max_row {
3648            return None;
3649        }
3650
3651        let mut target_indent = self.line_indent_for_row(buffer_row);
3652
3653        // If the current row is at the start of an indented block, we want to return this
3654        // block as the enclosing indent.
3655        if !target_indent.is_line_empty() && buffer_row < max_row {
3656            let next_line_indent = self.line_indent_for_row(buffer_row + 1);
3657            if !next_line_indent.is_line_empty()
3658                && target_indent.raw_len() < next_line_indent.raw_len()
3659            {
3660                target_indent = next_line_indent;
3661                buffer_row += 1;
3662            }
3663        }
3664
3665        const SEARCH_ROW_LIMIT: u32 = 25000;
3666        const SEARCH_WHITESPACE_ROW_LIMIT: u32 = 2500;
3667        const YIELD_INTERVAL: u32 = 100;
3668
3669        let mut accessed_row_counter = 0;
3670
3671        // If there is a blank line at the current row, search for the next non indented lines
3672        if target_indent.is_line_empty() {
3673            let start = buffer_row.saturating_sub(SEARCH_WHITESPACE_ROW_LIMIT);
3674            let end = (max_row + 1).min(buffer_row + SEARCH_WHITESPACE_ROW_LIMIT);
3675
3676            let mut non_empty_line_above = None;
3677            for (row, indent) in self
3678                .text
3679                .reversed_line_indents_in_row_range(start..buffer_row)
3680            {
3681                accessed_row_counter += 1;
3682                if accessed_row_counter == YIELD_INTERVAL {
3683                    accessed_row_counter = 0;
3684                    yield_now().await;
3685                }
3686                if !indent.is_line_empty() {
3687                    non_empty_line_above = Some((row, indent));
3688                    break;
3689                }
3690            }
3691
3692            let mut non_empty_line_below = None;
3693            for (row, indent) in self.text.line_indents_in_row_range((buffer_row + 1)..end) {
3694                accessed_row_counter += 1;
3695                if accessed_row_counter == YIELD_INTERVAL {
3696                    accessed_row_counter = 0;
3697                    yield_now().await;
3698                }
3699                if !indent.is_line_empty() {
3700                    non_empty_line_below = Some((row, indent));
3701                    break;
3702                }
3703            }
3704
3705            let (row, indent) = match (non_empty_line_above, non_empty_line_below) {
3706                (Some((above_row, above_indent)), Some((below_row, below_indent))) => {
3707                    if above_indent.raw_len() >= below_indent.raw_len() {
3708                        (above_row, above_indent)
3709                    } else {
3710                        (below_row, below_indent)
3711                    }
3712                }
3713                (Some(above), None) => above,
3714                (None, Some(below)) => below,
3715                _ => return None,
3716            };
3717
3718            target_indent = indent;
3719            buffer_row = row;
3720        }
3721
3722        let start = buffer_row.saturating_sub(SEARCH_ROW_LIMIT);
3723        let end = (max_row + 1).min(buffer_row + SEARCH_ROW_LIMIT);
3724
3725        let mut start_indent = None;
3726        for (row, indent) in self
3727            .text
3728            .reversed_line_indents_in_row_range(start..buffer_row)
3729        {
3730            accessed_row_counter += 1;
3731            if accessed_row_counter == YIELD_INTERVAL {
3732                accessed_row_counter = 0;
3733                yield_now().await;
3734            }
3735            if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
3736                start_indent = Some((row, indent));
3737                break;
3738            }
3739        }
3740        let (start_row, start_indent_size) = start_indent?;
3741
3742        let mut end_indent = (end, None);
3743        for (row, indent) in self.text.line_indents_in_row_range((buffer_row + 1)..end) {
3744            accessed_row_counter += 1;
3745            if accessed_row_counter == YIELD_INTERVAL {
3746                accessed_row_counter = 0;
3747                yield_now().await;
3748            }
3749            if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
3750                end_indent = (row.saturating_sub(1), Some(indent));
3751                break;
3752            }
3753        }
3754        let (end_row, end_indent_size) = end_indent;
3755
3756        let indent = if let Some(end_indent_size) = end_indent_size {
3757            if start_indent_size.raw_len() > end_indent_size.raw_len() {
3758                start_indent_size
3759            } else {
3760                end_indent_size
3761            }
3762        } else {
3763            start_indent_size
3764        };
3765
3766        Some((start_row..end_row, indent))
3767    }
3768
3769    /// Returns selections for remote peers intersecting the given range.
3770    #[allow(clippy::type_complexity)]
3771    pub fn selections_in_range(
3772        &self,
3773        range: Range<Anchor>,
3774        include_local: bool,
3775    ) -> impl Iterator<
3776        Item = (
3777            ReplicaId,
3778            bool,
3779            CursorShape,
3780            impl Iterator<Item = &Selection<Anchor>> + '_,
3781        ),
3782    > + '_ {
3783        self.remote_selections
3784            .iter()
3785            .filter(move |(replica_id, set)| {
3786                (include_local || **replica_id != self.text.replica_id())
3787                    && !set.selections.is_empty()
3788            })
3789            .map(move |(replica_id, set)| {
3790                let start_ix = match set.selections.binary_search_by(|probe| {
3791                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
3792                }) {
3793                    Ok(ix) | Err(ix) => ix,
3794                };
3795                let end_ix = match set.selections.binary_search_by(|probe| {
3796                    probe.start.cmp(&range.end, self).then(Ordering::Less)
3797                }) {
3798                    Ok(ix) | Err(ix) => ix,
3799                };
3800
3801                (
3802                    *replica_id,
3803                    set.line_mode,
3804                    set.cursor_shape,
3805                    set.selections[start_ix..end_ix].iter(),
3806                )
3807            })
3808    }
3809
3810    /// Whether the buffer contains any Git changes.
3811    pub fn has_git_diff(&self) -> bool {
3812        !self.git_diff.is_empty()
3813    }
3814
3815    /// Returns all the Git diff hunks intersecting the given row range.
3816    #[cfg(any(test, feature = "test-support"))]
3817    pub fn git_diff_hunks_in_row_range(
3818        &self,
3819        range: Range<BufferRow>,
3820    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk> {
3821        self.git_diff.hunks_in_row_range(range, self)
3822    }
3823
3824    /// Returns all the Git diff hunks intersecting the given
3825    /// range.
3826    pub fn git_diff_hunks_intersecting_range(
3827        &self,
3828        range: Range<Anchor>,
3829    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk> {
3830        self.git_diff.hunks_intersecting_range(range, self)
3831    }
3832
3833    /// Returns all the Git diff hunks intersecting the given
3834    /// range, in reverse order.
3835    pub fn git_diff_hunks_intersecting_range_rev(
3836        &self,
3837        range: Range<Anchor>,
3838    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk> {
3839        self.git_diff.hunks_intersecting_range_rev(range, self)
3840    }
3841
3842    /// Returns if the buffer contains any diagnostics.
3843    pub fn has_diagnostics(&self) -> bool {
3844        !self.diagnostics.is_empty()
3845    }
3846
3847    /// Returns all the diagnostics intersecting the given range.
3848    pub fn diagnostics_in_range<'a, T, O>(
3849        &'a self,
3850        search_range: Range<T>,
3851        reversed: bool,
3852    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3853    where
3854        T: 'a + Clone + ToOffset,
3855        O: 'a + FromAnchor + Ord,
3856    {
3857        let mut iterators: Vec<_> = self
3858            .diagnostics
3859            .iter()
3860            .map(|(_, collection)| {
3861                collection
3862                    .range::<T, O>(search_range.clone(), self, true, reversed)
3863                    .peekable()
3864            })
3865            .collect();
3866
3867        std::iter::from_fn(move || {
3868            let (next_ix, _) = iterators
3869                .iter_mut()
3870                .enumerate()
3871                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
3872                .min_by(|(_, a), (_, b)| {
3873                    let cmp = a
3874                        .range
3875                        .start
3876                        .cmp(&b.range.start)
3877                        // when range is equal, sort by diagnostic severity
3878                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
3879                        // and stabilize order with group_id
3880                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
3881                    if reversed {
3882                        cmp.reverse()
3883                    } else {
3884                        cmp
3885                    }
3886                })?;
3887            iterators[next_ix].next()
3888        })
3889    }
3890
3891    /// Returns all the diagnostic groups associated with the given
3892    /// language server ID. If no language server ID is provided,
3893    /// all diagnostics groups are returned.
3894    pub fn diagnostic_groups(
3895        &self,
3896        language_server_id: Option<LanguageServerId>,
3897    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
3898        let mut groups = Vec::new();
3899
3900        if let Some(language_server_id) = language_server_id {
3901            if let Ok(ix) = self
3902                .diagnostics
3903                .binary_search_by_key(&language_server_id, |e| e.0)
3904            {
3905                self.diagnostics[ix]
3906                    .1
3907                    .groups(language_server_id, &mut groups, self);
3908            }
3909        } else {
3910            for (language_server_id, diagnostics) in self.diagnostics.iter() {
3911                diagnostics.groups(*language_server_id, &mut groups, self);
3912            }
3913        }
3914
3915        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
3916            let a_start = &group_a.entries[group_a.primary_ix].range.start;
3917            let b_start = &group_b.entries[group_b.primary_ix].range.start;
3918            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
3919        });
3920
3921        groups
3922    }
3923
3924    /// Returns an iterator over the diagnostics for the given group.
3925    pub fn diagnostic_group<'a, O>(
3926        &'a self,
3927        group_id: usize,
3928    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3929    where
3930        O: 'a + FromAnchor,
3931    {
3932        self.diagnostics
3933            .iter()
3934            .flat_map(move |(_, set)| set.group(group_id, self))
3935    }
3936
3937    /// An integer version number that accounts for all updates besides
3938    /// the buffer's text itself (which is versioned via a version vector).
3939    pub fn non_text_state_update_count(&self) -> usize {
3940        self.non_text_state_update_count
3941    }
3942
3943    /// Returns a snapshot of underlying file.
3944    pub fn file(&self) -> Option<&Arc<dyn File>> {
3945        self.file.as_ref()
3946    }
3947
3948    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
3949    pub fn resolve_file_path(&self, cx: &AppContext, include_root: bool) -> Option<PathBuf> {
3950        if let Some(file) = self.file() {
3951            if file.path().file_name().is_none() || include_root {
3952                Some(file.full_path(cx))
3953            } else {
3954                Some(file.path().to_path_buf())
3955            }
3956        } else {
3957            None
3958        }
3959    }
3960}
3961
3962fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
3963    indent_size_for_text(text.chars_at(Point::new(row, 0)))
3964}
3965
3966fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
3967    let mut result = IndentSize::spaces(0);
3968    for c in text {
3969        let kind = match c {
3970            ' ' => IndentKind::Space,
3971            '\t' => IndentKind::Tab,
3972            _ => break,
3973        };
3974        if result.len == 0 {
3975            result.kind = kind;
3976        }
3977        result.len += 1;
3978    }
3979    result
3980}
3981
3982impl Clone for BufferSnapshot {
3983    fn clone(&self) -> Self {
3984        Self {
3985            text: self.text.clone(),
3986            git_diff: self.git_diff.clone(),
3987            syntax: self.syntax.clone(),
3988            file: self.file.clone(),
3989            remote_selections: self.remote_selections.clone(),
3990            diagnostics: self.diagnostics.clone(),
3991            language: self.language.clone(),
3992            non_text_state_update_count: self.non_text_state_update_count,
3993        }
3994    }
3995}
3996
3997impl Deref for BufferSnapshot {
3998    type Target = text::BufferSnapshot;
3999
4000    fn deref(&self) -> &Self::Target {
4001        &self.text
4002    }
4003}
4004
4005unsafe impl<'a> Send for BufferChunks<'a> {}
4006
4007impl<'a> BufferChunks<'a> {
4008    pub(crate) fn new(
4009        text: &'a Rope,
4010        range: Range<usize>,
4011        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
4012        diagnostics: bool,
4013        buffer_snapshot: Option<&'a BufferSnapshot>,
4014    ) -> Self {
4015        let mut highlights = None;
4016        if let Some((captures, highlight_maps)) = syntax {
4017            highlights = Some(BufferChunkHighlights {
4018                captures,
4019                next_capture: None,
4020                stack: Default::default(),
4021                highlight_maps,
4022            })
4023        }
4024
4025        let diagnostic_endpoints = diagnostics.then(|| Vec::new().into_iter().peekable());
4026        let chunks = text.chunks_in_range(range.clone());
4027
4028        let mut this = BufferChunks {
4029            range,
4030            buffer_snapshot,
4031            chunks,
4032            diagnostic_endpoints,
4033            error_depth: 0,
4034            warning_depth: 0,
4035            information_depth: 0,
4036            hint_depth: 0,
4037            unnecessary_depth: 0,
4038            highlights,
4039        };
4040        this.initialize_diagnostic_endpoints();
4041        this
4042    }
4043
4044    /// Seeks to the given byte offset in the buffer.
4045    pub fn seek(&mut self, range: Range<usize>) {
4046        let old_range = std::mem::replace(&mut self.range, range.clone());
4047        self.chunks.set_range(self.range.clone());
4048        if let Some(highlights) = self.highlights.as_mut() {
4049            if old_range.start <= self.range.start && old_range.end >= self.range.end {
4050                // Reuse existing highlights stack, as the new range is a subrange of the old one.
4051                highlights
4052                    .stack
4053                    .retain(|(end_offset, _)| *end_offset > range.start);
4054                if let Some(capture) = &highlights.next_capture {
4055                    if range.start >= capture.node.start_byte() {
4056                        let next_capture_end = capture.node.end_byte();
4057                        if range.start < next_capture_end {
4058                            highlights.stack.push((
4059                                next_capture_end,
4060                                highlights.highlight_maps[capture.grammar_index].get(capture.index),
4061                            ));
4062                        }
4063                        highlights.next_capture.take();
4064                    }
4065                }
4066            } else if let Some(snapshot) = self.buffer_snapshot {
4067                let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
4068                *highlights = BufferChunkHighlights {
4069                    captures,
4070                    next_capture: None,
4071                    stack: Default::default(),
4072                    highlight_maps,
4073                };
4074            } else {
4075                // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
4076                // Seeking such BufferChunks is not supported.
4077                debug_assert!(false, "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot");
4078            }
4079
4080            highlights.captures.set_byte_range(self.range.clone());
4081            self.initialize_diagnostic_endpoints();
4082        }
4083    }
4084
4085    fn initialize_diagnostic_endpoints(&mut self) {
4086        if let Some(diagnostics) = self.diagnostic_endpoints.as_mut() {
4087            if let Some(buffer) = self.buffer_snapshot {
4088                let mut diagnostic_endpoints = Vec::new();
4089                for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
4090                    diagnostic_endpoints.push(DiagnosticEndpoint {
4091                        offset: entry.range.start,
4092                        is_start: true,
4093                        severity: entry.diagnostic.severity,
4094                        is_unnecessary: entry.diagnostic.is_unnecessary,
4095                    });
4096                    diagnostic_endpoints.push(DiagnosticEndpoint {
4097                        offset: entry.range.end,
4098                        is_start: false,
4099                        severity: entry.diagnostic.severity,
4100                        is_unnecessary: entry.diagnostic.is_unnecessary,
4101                    });
4102                }
4103                diagnostic_endpoints
4104                    .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
4105                *diagnostics = diagnostic_endpoints.into_iter().peekable();
4106            }
4107        }
4108    }
4109
4110    /// The current byte offset in the buffer.
4111    pub fn offset(&self) -> usize {
4112        self.range.start
4113    }
4114
4115    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
4116        let depth = match endpoint.severity {
4117            DiagnosticSeverity::ERROR => &mut self.error_depth,
4118            DiagnosticSeverity::WARNING => &mut self.warning_depth,
4119            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
4120            DiagnosticSeverity::HINT => &mut self.hint_depth,
4121            _ => return,
4122        };
4123        if endpoint.is_start {
4124            *depth += 1;
4125        } else {
4126            *depth -= 1;
4127        }
4128
4129        if endpoint.is_unnecessary {
4130            if endpoint.is_start {
4131                self.unnecessary_depth += 1;
4132            } else {
4133                self.unnecessary_depth -= 1;
4134            }
4135        }
4136    }
4137
4138    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
4139        if self.error_depth > 0 {
4140            Some(DiagnosticSeverity::ERROR)
4141        } else if self.warning_depth > 0 {
4142            Some(DiagnosticSeverity::WARNING)
4143        } else if self.information_depth > 0 {
4144            Some(DiagnosticSeverity::INFORMATION)
4145        } else if self.hint_depth > 0 {
4146            Some(DiagnosticSeverity::HINT)
4147        } else {
4148            None
4149        }
4150    }
4151
4152    fn current_code_is_unnecessary(&self) -> bool {
4153        self.unnecessary_depth > 0
4154    }
4155}
4156
4157impl<'a> Iterator for BufferChunks<'a> {
4158    type Item = Chunk<'a>;
4159
4160    fn next(&mut self) -> Option<Self::Item> {
4161        let mut next_capture_start = usize::MAX;
4162        let mut next_diagnostic_endpoint = usize::MAX;
4163
4164        if let Some(highlights) = self.highlights.as_mut() {
4165            while let Some((parent_capture_end, _)) = highlights.stack.last() {
4166                if *parent_capture_end <= self.range.start {
4167                    highlights.stack.pop();
4168                } else {
4169                    break;
4170                }
4171            }
4172
4173            if highlights.next_capture.is_none() {
4174                highlights.next_capture = highlights.captures.next();
4175            }
4176
4177            while let Some(capture) = highlights.next_capture.as_ref() {
4178                if self.range.start < capture.node.start_byte() {
4179                    next_capture_start = capture.node.start_byte();
4180                    break;
4181                } else {
4182                    let highlight_id =
4183                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
4184                    highlights
4185                        .stack
4186                        .push((capture.node.end_byte(), highlight_id));
4187                    highlights.next_capture = highlights.captures.next();
4188                }
4189            }
4190        }
4191
4192        let mut diagnostic_endpoints = std::mem::take(&mut self.diagnostic_endpoints);
4193        if let Some(diagnostic_endpoints) = diagnostic_endpoints.as_mut() {
4194            while let Some(endpoint) = diagnostic_endpoints.peek().copied() {
4195                if endpoint.offset <= self.range.start {
4196                    self.update_diagnostic_depths(endpoint);
4197                    diagnostic_endpoints.next();
4198                } else {
4199                    next_diagnostic_endpoint = endpoint.offset;
4200                    break;
4201                }
4202            }
4203        }
4204        self.diagnostic_endpoints = diagnostic_endpoints;
4205
4206        if let Some(chunk) = self.chunks.peek() {
4207            let chunk_start = self.range.start;
4208            let mut chunk_end = (self.chunks.offset() + chunk.len())
4209                .min(next_capture_start)
4210                .min(next_diagnostic_endpoint);
4211            let mut highlight_id = None;
4212            if let Some(highlights) = self.highlights.as_ref() {
4213                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
4214                    chunk_end = chunk_end.min(*parent_capture_end);
4215                    highlight_id = Some(*parent_highlight_id);
4216                }
4217            }
4218
4219            let slice =
4220                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
4221            self.range.start = chunk_end;
4222            if self.range.start == self.chunks.offset() + chunk.len() {
4223                self.chunks.next().unwrap();
4224            }
4225
4226            Some(Chunk {
4227                text: slice,
4228                syntax_highlight_id: highlight_id,
4229                diagnostic_severity: self.current_diagnostic_severity(),
4230                is_unnecessary: self.current_code_is_unnecessary(),
4231                ..Default::default()
4232            })
4233        } else {
4234            None
4235        }
4236    }
4237}
4238
4239impl operation_queue::Operation for Operation {
4240    fn lamport_timestamp(&self) -> clock::Lamport {
4241        match self {
4242            Operation::Buffer(_) => {
4243                unreachable!("buffer operations should never be deferred at this layer")
4244            }
4245            Operation::UpdateDiagnostics {
4246                lamport_timestamp, ..
4247            }
4248            | Operation::UpdateSelections {
4249                lamport_timestamp, ..
4250            }
4251            | Operation::UpdateCompletionTriggers {
4252                lamport_timestamp, ..
4253            } => *lamport_timestamp,
4254        }
4255    }
4256}
4257
4258impl Default for Diagnostic {
4259    fn default() -> Self {
4260        Self {
4261            source: Default::default(),
4262            code: None,
4263            severity: DiagnosticSeverity::ERROR,
4264            message: Default::default(),
4265            group_id: 0,
4266            is_primary: false,
4267            is_disk_based: false,
4268            is_unnecessary: false,
4269            data: None,
4270        }
4271    }
4272}
4273
4274impl IndentSize {
4275    /// Returns an [`IndentSize`] representing the given spaces.
4276    pub fn spaces(len: u32) -> Self {
4277        Self {
4278            len,
4279            kind: IndentKind::Space,
4280        }
4281    }
4282
4283    /// Returns an [`IndentSize`] representing a tab.
4284    pub fn tab() -> Self {
4285        Self {
4286            len: 1,
4287            kind: IndentKind::Tab,
4288        }
4289    }
4290
4291    /// An iterator over the characters represented by this [`IndentSize`].
4292    pub fn chars(&self) -> impl Iterator<Item = char> {
4293        iter::repeat(self.char()).take(self.len as usize)
4294    }
4295
4296    /// The character representation of this [`IndentSize`].
4297    pub fn char(&self) -> char {
4298        match self.kind {
4299            IndentKind::Space => ' ',
4300            IndentKind::Tab => '\t',
4301        }
4302    }
4303
4304    /// Consumes the current [`IndentSize`] and returns a new one that has
4305    /// been shrunk or enlarged by the given size along the given direction.
4306    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4307        match direction {
4308            Ordering::Less => {
4309                if self.kind == size.kind && self.len >= size.len {
4310                    self.len -= size.len;
4311                }
4312            }
4313            Ordering::Equal => {}
4314            Ordering::Greater => {
4315                if self.len == 0 {
4316                    self = size;
4317                } else if self.kind == size.kind {
4318                    self.len += size.len;
4319                }
4320            }
4321        }
4322        self
4323    }
4324}
4325
4326#[cfg(any(test, feature = "test-support"))]
4327pub struct TestFile {
4328    pub path: Arc<Path>,
4329    pub root_name: String,
4330}
4331
4332#[cfg(any(test, feature = "test-support"))]
4333impl File for TestFile {
4334    fn path(&self) -> &Arc<Path> {
4335        &self.path
4336    }
4337
4338    fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
4339        PathBuf::from(&self.root_name).join(self.path.as_ref())
4340    }
4341
4342    fn as_local(&self) -> Option<&dyn LocalFile> {
4343        None
4344    }
4345
4346    fn mtime(&self) -> Option<SystemTime> {
4347        unimplemented!()
4348    }
4349
4350    fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
4351        self.path().file_name().unwrap_or(self.root_name.as_ref())
4352    }
4353
4354    fn worktree_id(&self, _: &AppContext) -> WorktreeId {
4355        WorktreeId::from_usize(0)
4356    }
4357
4358    fn is_deleted(&self) -> bool {
4359        unimplemented!()
4360    }
4361
4362    fn as_any(&self) -> &dyn std::any::Any {
4363        unimplemented!()
4364    }
4365
4366    fn to_proto(&self, _: &AppContext) -> rpc::proto::File {
4367        unimplemented!()
4368    }
4369
4370    fn is_private(&self) -> bool {
4371        false
4372    }
4373}
4374
4375pub(crate) fn contiguous_ranges(
4376    values: impl Iterator<Item = u32>,
4377    max_len: usize,
4378) -> impl Iterator<Item = Range<u32>> {
4379    let mut values = values;
4380    let mut current_range: Option<Range<u32>> = None;
4381    std::iter::from_fn(move || loop {
4382        if let Some(value) = values.next() {
4383            if let Some(range) = &mut current_range {
4384                if value == range.end && range.len() < max_len {
4385                    range.end += 1;
4386                    continue;
4387                }
4388            }
4389
4390            let prev_range = current_range.clone();
4391            current_range = Some(value..(value + 1));
4392            if prev_range.is_some() {
4393                return prev_range;
4394            }
4395        } else {
4396            return current_range.take();
4397        }
4398    })
4399}
4400
4401#[derive(Default, Debug)]
4402pub struct CharClassifier {
4403    scope: Option<LanguageScope>,
4404    for_completion: bool,
4405    ignore_punctuation: bool,
4406}
4407
4408impl CharClassifier {
4409    pub fn new(scope: Option<LanguageScope>) -> Self {
4410        Self {
4411            scope,
4412            for_completion: false,
4413            ignore_punctuation: false,
4414        }
4415    }
4416
4417    pub fn for_completion(self, for_completion: bool) -> Self {
4418        Self {
4419            for_completion,
4420            ..self
4421        }
4422    }
4423
4424    pub fn ignore_punctuation(self, ignore_punctuation: bool) -> Self {
4425        Self {
4426            ignore_punctuation,
4427            ..self
4428        }
4429    }
4430
4431    pub fn is_whitespace(&self, c: char) -> bool {
4432        self.kind(c) == CharKind::Whitespace
4433    }
4434
4435    pub fn is_word(&self, c: char) -> bool {
4436        self.kind(c) == CharKind::Word
4437    }
4438
4439    pub fn is_punctuation(&self, c: char) -> bool {
4440        self.kind(c) == CharKind::Punctuation
4441    }
4442
4443    pub fn kind(&self, c: char) -> CharKind {
4444        if c.is_whitespace() {
4445            return CharKind::Whitespace;
4446        } else if c.is_alphanumeric() || c == '_' {
4447            return CharKind::Word;
4448        }
4449
4450        if let Some(scope) = &self.scope {
4451            if let Some(characters) = scope.word_characters() {
4452                if characters.contains(&c) {
4453                    if c == '-' && !self.for_completion && !self.ignore_punctuation {
4454                        return CharKind::Punctuation;
4455                    }
4456                    return CharKind::Word;
4457                }
4458            }
4459        }
4460
4461        if self.ignore_punctuation {
4462            CharKind::Word
4463        } else {
4464            CharKind::Punctuation
4465        }
4466    }
4467}
4468
4469/// Find all of the ranges of whitespace that occur at the ends of lines
4470/// in the given rope.
4471///
4472/// This could also be done with a regex search, but this implementation
4473/// avoids copying text.
4474pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4475    let mut ranges = Vec::new();
4476
4477    let mut offset = 0;
4478    let mut prev_chunk_trailing_whitespace_range = 0..0;
4479    for chunk in rope.chunks() {
4480        let mut prev_line_trailing_whitespace_range = 0..0;
4481        for (i, line) in chunk.split('\n').enumerate() {
4482            let line_end_offset = offset + line.len();
4483            let trimmed_line_len = line.trim_end_matches([' ', '\t']).len();
4484            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4485
4486            if i == 0 && trimmed_line_len == 0 {
4487                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4488            }
4489            if !prev_line_trailing_whitespace_range.is_empty() {
4490                ranges.push(prev_line_trailing_whitespace_range);
4491            }
4492
4493            offset = line_end_offset + 1;
4494            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4495        }
4496
4497        offset -= 1;
4498        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4499    }
4500
4501    if !prev_chunk_trailing_whitespace_range.is_empty() {
4502        ranges.push(prev_chunk_trailing_whitespace_range);
4503    }
4504
4505    ranges
4506}