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