buffer.rs

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