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