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        self.selections_update_count += 1;
1705        cx.notify();
1706    }
1707
1708    /// Clears the selections, so that other replicas of the buffer do not see any selections for
1709    /// this replica.
1710    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1711        if self
1712            .remote_selections
1713            .get(&self.text.replica_id())
1714            .map_or(true, |set| !set.selections.is_empty())
1715        {
1716            self.set_active_selections(Arc::from([]), false, Default::default(), cx);
1717        }
1718    }
1719
1720    /// Replaces the buffer's entire text.
1721    pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Lamport>
1722    where
1723        T: Into<Arc<str>>,
1724    {
1725        self.autoindent_requests.clear();
1726        self.edit([(0..self.len(), text)], None, cx)
1727    }
1728
1729    /// Applies the given edits to the buffer. Each edit is specified as a range of text to
1730    /// delete, and a string of text to insert at that location.
1731    ///
1732    /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
1733    /// request for the edited ranges, which will be processed when the buffer finishes
1734    /// parsing.
1735    ///
1736    /// Parsing takes place at the end of a transaction, and may compute synchronously
1737    /// or asynchronously, depending on the changes.
1738    pub fn edit<I, S, T>(
1739        &mut self,
1740        edits_iter: I,
1741        autoindent_mode: Option<AutoindentMode>,
1742        cx: &mut ModelContext<Self>,
1743    ) -> Option<clock::Lamport>
1744    where
1745        I: IntoIterator<Item = (Range<S>, T)>,
1746        S: ToOffset,
1747        T: Into<Arc<str>>,
1748    {
1749        // Skip invalid edits and coalesce contiguous ones.
1750        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1751        for (range, new_text) in edits_iter {
1752            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1753            if range.start > range.end {
1754                mem::swap(&mut range.start, &mut range.end);
1755            }
1756            let new_text = new_text.into();
1757            if !new_text.is_empty() || !range.is_empty() {
1758                if let Some((prev_range, prev_text)) = edits.last_mut() {
1759                    if prev_range.end >= range.start {
1760                        prev_range.end = cmp::max(prev_range.end, range.end);
1761                        *prev_text = format!("{prev_text}{new_text}").into();
1762                    } else {
1763                        edits.push((range, new_text));
1764                    }
1765                } else {
1766                    edits.push((range, new_text));
1767                }
1768            }
1769        }
1770        if edits.is_empty() {
1771            return None;
1772        }
1773
1774        self.start_transaction();
1775        self.pending_autoindent.take();
1776        let autoindent_request = autoindent_mode
1777            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
1778
1779        let edit_operation = self.text.edit(edits.iter().cloned());
1780        let edit_id = edit_operation.timestamp();
1781
1782        if let Some((before_edit, mode)) = autoindent_request {
1783            let mut delta = 0isize;
1784            let entries = edits
1785                .into_iter()
1786                .enumerate()
1787                .zip(&edit_operation.as_edit().unwrap().new_text)
1788                .map(|((ix, (range, _)), new_text)| {
1789                    let new_text_length = new_text.len();
1790                    let old_start = range.start.to_point(&before_edit);
1791                    let new_start = (delta + range.start as isize) as usize;
1792                    delta += new_text_length as isize - (range.end as isize - range.start as isize);
1793
1794                    let mut range_of_insertion_to_indent = 0..new_text_length;
1795                    let mut first_line_is_new = false;
1796                    let mut original_indent_column = None;
1797
1798                    // When inserting an entire line at the beginning of an existing line,
1799                    // treat the insertion as new.
1800                    if new_text.contains('\n')
1801                        && old_start.column <= before_edit.indent_size_for_line(old_start.row).len
1802                    {
1803                        first_line_is_new = true;
1804                    }
1805
1806                    // When inserting text starting with a newline, avoid auto-indenting the
1807                    // previous line.
1808                    if new_text.starts_with('\n') {
1809                        range_of_insertion_to_indent.start += 1;
1810                        first_line_is_new = true;
1811                    }
1812
1813                    // Avoid auto-indenting after the insertion.
1814                    if let AutoindentMode::Block {
1815                        original_indent_columns,
1816                    } = &mode
1817                    {
1818                        original_indent_column =
1819                            Some(original_indent_columns.get(ix).copied().unwrap_or_else(|| {
1820                                indent_size_for_text(
1821                                    new_text[range_of_insertion_to_indent.clone()].chars(),
1822                                )
1823                                .len
1824                            }));
1825                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
1826                            range_of_insertion_to_indent.end -= 1;
1827                        }
1828                    }
1829
1830                    AutoindentRequestEntry {
1831                        first_line_is_new,
1832                        original_indent_column,
1833                        indent_size: before_edit.language_indent_size_at(range.start, cx),
1834                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
1835                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
1836                    }
1837                })
1838                .collect();
1839
1840            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1841                before_edit,
1842                entries,
1843                is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
1844            }));
1845        }
1846
1847        self.end_transaction(cx);
1848        self.send_operation(Operation::Buffer(edit_operation), cx);
1849        Some(edit_id)
1850    }
1851
1852    fn did_edit(
1853        &mut self,
1854        old_version: &clock::Global,
1855        was_dirty: bool,
1856        cx: &mut ModelContext<Self>,
1857    ) {
1858        if self.edits_since::<usize>(old_version).next().is_none() {
1859            return;
1860        }
1861
1862        self.reparse(cx);
1863
1864        cx.emit(Event::Edited);
1865        if was_dirty != self.is_dirty() {
1866            cx.emit(Event::DirtyChanged);
1867        }
1868        cx.notify();
1869    }
1870
1871    /// Applies the given remote operations to the buffer.
1872    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1873        &mut self,
1874        ops: I,
1875        cx: &mut ModelContext<Self>,
1876    ) -> Result<()> {
1877        self.pending_autoindent.take();
1878        let was_dirty = self.is_dirty();
1879        let old_version = self.version.clone();
1880        let mut deferred_ops = Vec::new();
1881        let buffer_ops = ops
1882            .into_iter()
1883            .filter_map(|op| match op {
1884                Operation::Buffer(op) => Some(op),
1885                _ => {
1886                    if self.can_apply_op(&op) {
1887                        self.apply_op(op, cx);
1888                    } else {
1889                        deferred_ops.push(op);
1890                    }
1891                    None
1892                }
1893            })
1894            .collect::<Vec<_>>();
1895        self.text.apply_ops(buffer_ops)?;
1896        self.deferred_ops.insert(deferred_ops);
1897        self.flush_deferred_ops(cx);
1898        self.did_edit(&old_version, was_dirty, cx);
1899        // Notify independently of whether the buffer was edited as the operations could include a
1900        // selection update.
1901        cx.notify();
1902        Ok(())
1903    }
1904
1905    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1906        let mut deferred_ops = Vec::new();
1907        for op in self.deferred_ops.drain().iter().cloned() {
1908            if self.can_apply_op(&op) {
1909                self.apply_op(op, cx);
1910            } else {
1911                deferred_ops.push(op);
1912            }
1913        }
1914        self.deferred_ops.insert(deferred_ops);
1915    }
1916
1917    fn can_apply_op(&self, operation: &Operation) -> bool {
1918        match operation {
1919            Operation::Buffer(_) => {
1920                unreachable!("buffer operations should never be applied at this layer")
1921            }
1922            Operation::UpdateDiagnostics {
1923                diagnostics: diagnostic_set,
1924                ..
1925            } => diagnostic_set.iter().all(|diagnostic| {
1926                self.text.can_resolve(&diagnostic.range.start)
1927                    && self.text.can_resolve(&diagnostic.range.end)
1928            }),
1929            Operation::UpdateSelections { selections, .. } => selections
1930                .iter()
1931                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1932            Operation::UpdateCompletionTriggers { .. } => true,
1933        }
1934    }
1935
1936    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1937        match operation {
1938            Operation::Buffer(_) => {
1939                unreachable!("buffer operations should never be applied at this layer")
1940            }
1941            Operation::UpdateDiagnostics {
1942                server_id,
1943                diagnostics: diagnostic_set,
1944                lamport_timestamp,
1945            } => {
1946                let snapshot = self.snapshot();
1947                self.apply_diagnostic_update(
1948                    server_id,
1949                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1950                    lamport_timestamp,
1951                    cx,
1952                );
1953            }
1954            Operation::UpdateSelections {
1955                selections,
1956                lamport_timestamp,
1957                line_mode,
1958                cursor_shape,
1959            } => {
1960                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
1961                    if set.lamport_timestamp > lamport_timestamp {
1962                        return;
1963                    }
1964                }
1965
1966                self.remote_selections.insert(
1967                    lamport_timestamp.replica_id,
1968                    SelectionSet {
1969                        selections,
1970                        lamport_timestamp,
1971                        line_mode,
1972                        cursor_shape,
1973                    },
1974                );
1975                self.text.lamport_clock.observe(lamport_timestamp);
1976                self.selections_update_count += 1;
1977            }
1978            Operation::UpdateCompletionTriggers {
1979                triggers,
1980                lamport_timestamp,
1981            } => {
1982                self.completion_triggers = triggers;
1983                self.text.lamport_clock.observe(lamport_timestamp);
1984            }
1985        }
1986    }
1987
1988    fn apply_diagnostic_update(
1989        &mut self,
1990        server_id: LanguageServerId,
1991        diagnostics: DiagnosticSet,
1992        lamport_timestamp: clock::Lamport,
1993        cx: &mut ModelContext<Self>,
1994    ) {
1995        if lamport_timestamp > self.diagnostics_timestamp {
1996            let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
1997            if diagnostics.len() == 0 {
1998                if let Ok(ix) = ix {
1999                    self.diagnostics.remove(ix);
2000                }
2001            } else {
2002                match ix {
2003                    Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
2004                    Ok(ix) => self.diagnostics[ix].1 = diagnostics,
2005                };
2006            }
2007            self.diagnostics_timestamp = lamport_timestamp;
2008            self.diagnostics_update_count += 1;
2009            self.text.lamport_clock.observe(lamport_timestamp);
2010            cx.notify();
2011            cx.emit(Event::DiagnosticsUpdated);
2012        }
2013    }
2014
2015    fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
2016        cx.emit(Event::Operation(operation));
2017    }
2018
2019    /// Removes the selections for a given peer.
2020    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
2021        self.remote_selections.remove(&replica_id);
2022        cx.notify();
2023    }
2024
2025    /// Undoes the most recent transaction.
2026    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
2027        let was_dirty = self.is_dirty();
2028        let old_version = self.version.clone();
2029
2030        if let Some((transaction_id, operation)) = self.text.undo() {
2031            self.send_operation(Operation::Buffer(operation), cx);
2032            self.did_edit(&old_version, was_dirty, cx);
2033            Some(transaction_id)
2034        } else {
2035            None
2036        }
2037    }
2038
2039    /// Manually undoes a specific transaction in the buffer's undo history.
2040    pub fn undo_transaction(
2041        &mut self,
2042        transaction_id: TransactionId,
2043        cx: &mut ModelContext<Self>,
2044    ) -> bool {
2045        let was_dirty = self.is_dirty();
2046        let old_version = self.version.clone();
2047        if let Some(operation) = self.text.undo_transaction(transaction_id) {
2048            self.send_operation(Operation::Buffer(operation), cx);
2049            self.did_edit(&old_version, was_dirty, cx);
2050            true
2051        } else {
2052            false
2053        }
2054    }
2055
2056    /// Manually undoes all changes after a given transaction in the buffer's undo history.
2057    pub fn undo_to_transaction(
2058        &mut self,
2059        transaction_id: TransactionId,
2060        cx: &mut ModelContext<Self>,
2061    ) -> bool {
2062        let was_dirty = self.is_dirty();
2063        let old_version = self.version.clone();
2064
2065        let operations = self.text.undo_to_transaction(transaction_id);
2066        let undone = !operations.is_empty();
2067        for operation in operations {
2068            self.send_operation(Operation::Buffer(operation), cx);
2069        }
2070        if undone {
2071            self.did_edit(&old_version, was_dirty, cx)
2072        }
2073        undone
2074    }
2075
2076    /// Manually redoes a specific transaction in the buffer's redo history.
2077    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
2078        let was_dirty = self.is_dirty();
2079        let old_version = self.version.clone();
2080
2081        if let Some((transaction_id, operation)) = self.text.redo() {
2082            self.send_operation(Operation::Buffer(operation), cx);
2083            self.did_edit(&old_version, was_dirty, cx);
2084            Some(transaction_id)
2085        } else {
2086            None
2087        }
2088    }
2089
2090    /// Manually undoes all changes until a given transaction in the buffer's redo history.
2091    pub fn redo_to_transaction(
2092        &mut self,
2093        transaction_id: TransactionId,
2094        cx: &mut ModelContext<Self>,
2095    ) -> bool {
2096        let was_dirty = self.is_dirty();
2097        let old_version = self.version.clone();
2098
2099        let operations = self.text.redo_to_transaction(transaction_id);
2100        let redone = !operations.is_empty();
2101        for operation in operations {
2102            self.send_operation(Operation::Buffer(operation), cx);
2103        }
2104        if redone {
2105            self.did_edit(&old_version, was_dirty, cx)
2106        }
2107        redone
2108    }
2109
2110    /// Override current completion triggers with the user-provided completion triggers.
2111    pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
2112        self.completion_triggers.clone_from(&triggers);
2113        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2114        self.send_operation(
2115            Operation::UpdateCompletionTriggers {
2116                triggers,
2117                lamport_timestamp: self.completion_triggers_timestamp,
2118            },
2119            cx,
2120        );
2121        cx.notify();
2122    }
2123
2124    /// Returns a list of strings which trigger a completion menu for this language.
2125    /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2126    pub fn completion_triggers(&self) -> &[String] {
2127        &self.completion_triggers
2128    }
2129}
2130
2131#[doc(hidden)]
2132#[cfg(any(test, feature = "test-support"))]
2133impl Buffer {
2134    pub fn edit_via_marked_text(
2135        &mut self,
2136        marked_string: &str,
2137        autoindent_mode: Option<AutoindentMode>,
2138        cx: &mut ModelContext<Self>,
2139    ) {
2140        let edits = self.edits_for_marked_text(marked_string);
2141        self.edit(edits, autoindent_mode, cx);
2142    }
2143
2144    pub fn set_group_interval(&mut self, group_interval: Duration) {
2145        self.text.set_group_interval(group_interval);
2146    }
2147
2148    pub fn randomly_edit<T>(
2149        &mut self,
2150        rng: &mut T,
2151        old_range_count: usize,
2152        cx: &mut ModelContext<Self>,
2153    ) where
2154        T: rand::Rng,
2155    {
2156        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2157        let mut last_end = None;
2158        for _ in 0..old_range_count {
2159            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2160                break;
2161            }
2162
2163            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2164            let mut range = self.random_byte_range(new_start, rng);
2165            if rng.gen_bool(0.2) {
2166                mem::swap(&mut range.start, &mut range.end);
2167            }
2168            last_end = Some(range.end);
2169
2170            let new_text_len = rng.gen_range(0..10);
2171            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2172
2173            edits.push((range, new_text));
2174        }
2175        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2176        self.edit(edits, None, cx);
2177    }
2178
2179    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
2180        let was_dirty = self.is_dirty();
2181        let old_version = self.version.clone();
2182
2183        let ops = self.text.randomly_undo_redo(rng);
2184        if !ops.is_empty() {
2185            for op in ops {
2186                self.send_operation(Operation::Buffer(op), cx);
2187                self.did_edit(&old_version, was_dirty, cx);
2188            }
2189        }
2190    }
2191}
2192
2193impl EventEmitter<Event> for Buffer {}
2194
2195impl Deref for Buffer {
2196    type Target = TextBuffer;
2197
2198    fn deref(&self) -> &Self::Target {
2199        &self.text
2200    }
2201}
2202
2203impl BufferSnapshot {
2204    /// Returns [`IndentSize`] for a given line that respects user settings and /// language preferences.
2205    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2206        indent_size_for_line(self, row)
2207    }
2208    /// Returns [`IndentSize`] for a given position that respects user settings
2209    /// and language preferences.
2210    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &AppContext) -> IndentSize {
2211        let settings = language_settings(self.language_at(position), self.file(), cx);
2212        if settings.hard_tabs {
2213            IndentSize::tab()
2214        } else {
2215            IndentSize::spaces(settings.tab_size.get())
2216        }
2217    }
2218
2219    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2220    /// is passed in as `single_indent_size`.
2221    pub fn suggested_indents(
2222        &self,
2223        rows: impl Iterator<Item = u32>,
2224        single_indent_size: IndentSize,
2225    ) -> BTreeMap<u32, IndentSize> {
2226        let mut result = BTreeMap::new();
2227
2228        for row_range in contiguous_ranges(rows, 10) {
2229            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2230                Some(suggestions) => suggestions,
2231                _ => break,
2232            };
2233
2234            for (row, suggestion) in row_range.zip(suggestions) {
2235                let indent_size = if let Some(suggestion) = suggestion {
2236                    result
2237                        .get(&suggestion.basis_row)
2238                        .copied()
2239                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2240                        .with_delta(suggestion.delta, single_indent_size)
2241                } else {
2242                    self.indent_size_for_line(row)
2243                };
2244
2245                result.insert(row, indent_size);
2246            }
2247        }
2248
2249        result
2250    }
2251
2252    fn suggest_autoindents(
2253        &self,
2254        row_range: Range<u32>,
2255    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2256        let config = &self.language.as_ref()?.config;
2257        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2258
2259        // Find the suggested indentation ranges based on the syntax tree.
2260        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2261        let end = Point::new(row_range.end, 0);
2262        let range = (start..end).to_offset(&self.text);
2263        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2264            Some(&grammar.indents_config.as_ref()?.query)
2265        });
2266        let indent_configs = matches
2267            .grammars()
2268            .iter()
2269            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2270            .collect::<Vec<_>>();
2271
2272        let mut indent_ranges = Vec::<Range<Point>>::new();
2273        let mut outdent_positions = Vec::<Point>::new();
2274        while let Some(mat) = matches.peek() {
2275            let mut start: Option<Point> = None;
2276            let mut end: Option<Point> = None;
2277
2278            let config = &indent_configs[mat.grammar_index];
2279            for capture in mat.captures {
2280                if capture.index == config.indent_capture_ix {
2281                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2282                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2283                } else if Some(capture.index) == config.start_capture_ix {
2284                    start = Some(Point::from_ts_point(capture.node.end_position()));
2285                } else if Some(capture.index) == config.end_capture_ix {
2286                    end = Some(Point::from_ts_point(capture.node.start_position()));
2287                } else if Some(capture.index) == config.outdent_capture_ix {
2288                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2289                }
2290            }
2291
2292            matches.advance();
2293            if let Some((start, end)) = start.zip(end) {
2294                if start.row == end.row {
2295                    continue;
2296                }
2297
2298                let range = start..end;
2299                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2300                    Err(ix) => indent_ranges.insert(ix, range),
2301                    Ok(ix) => {
2302                        let prev_range = &mut indent_ranges[ix];
2303                        prev_range.end = prev_range.end.max(range.end);
2304                    }
2305                }
2306            }
2307        }
2308
2309        let mut error_ranges = Vec::<Range<Point>>::new();
2310        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2311            Some(&grammar.error_query)
2312        });
2313        while let Some(mat) = matches.peek() {
2314            let node = mat.captures[0].node;
2315            let start = Point::from_ts_point(node.start_position());
2316            let end = Point::from_ts_point(node.end_position());
2317            let range = start..end;
2318            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2319                Ok(ix) | Err(ix) => ix,
2320            };
2321            let mut end_ix = ix;
2322            while let Some(existing_range) = error_ranges.get(end_ix) {
2323                if existing_range.end < end {
2324                    end_ix += 1;
2325                } else {
2326                    break;
2327                }
2328            }
2329            error_ranges.splice(ix..end_ix, [range]);
2330            matches.advance();
2331        }
2332
2333        outdent_positions.sort();
2334        for outdent_position in outdent_positions {
2335            // find the innermost indent range containing this outdent_position
2336            // set its end to the outdent position
2337            if let Some(range_to_truncate) = indent_ranges
2338                .iter_mut()
2339                .filter(|indent_range| indent_range.contains(&outdent_position))
2340                .last()
2341            {
2342                range_to_truncate.end = outdent_position;
2343            }
2344        }
2345
2346        // Find the suggested indentation increases and decreased based on regexes.
2347        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2348        self.for_each_line(
2349            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2350                ..Point::new(row_range.end, 0),
2351            |row, line| {
2352                if config
2353                    .decrease_indent_pattern
2354                    .as_ref()
2355                    .map_or(false, |regex| regex.is_match(line))
2356                {
2357                    indent_change_rows.push((row, Ordering::Less));
2358                }
2359                if config
2360                    .increase_indent_pattern
2361                    .as_ref()
2362                    .map_or(false, |regex| regex.is_match(line))
2363                {
2364                    indent_change_rows.push((row + 1, Ordering::Greater));
2365                }
2366            },
2367        );
2368
2369        let mut indent_changes = indent_change_rows.into_iter().peekable();
2370        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2371            prev_non_blank_row.unwrap_or(0)
2372        } else {
2373            row_range.start.saturating_sub(1)
2374        };
2375        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2376        Some(row_range.map(move |row| {
2377            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2378
2379            let mut indent_from_prev_row = false;
2380            let mut outdent_from_prev_row = false;
2381            let mut outdent_to_row = u32::MAX;
2382
2383            while let Some((indent_row, delta)) = indent_changes.peek() {
2384                match indent_row.cmp(&row) {
2385                    Ordering::Equal => match delta {
2386                        Ordering::Less => outdent_from_prev_row = true,
2387                        Ordering::Greater => indent_from_prev_row = true,
2388                        _ => {}
2389                    },
2390
2391                    Ordering::Greater => break,
2392                    Ordering::Less => {}
2393                }
2394
2395                indent_changes.next();
2396            }
2397
2398            for range in &indent_ranges {
2399                if range.start.row >= row {
2400                    break;
2401                }
2402                if range.start.row == prev_row && range.end > row_start {
2403                    indent_from_prev_row = true;
2404                }
2405                if range.end > prev_row_start && range.end <= row_start {
2406                    outdent_to_row = outdent_to_row.min(range.start.row);
2407                }
2408            }
2409
2410            let within_error = error_ranges
2411                .iter()
2412                .any(|e| e.start.row < row && e.end > row_start);
2413
2414            let suggestion = if outdent_to_row == prev_row
2415                || (outdent_from_prev_row && indent_from_prev_row)
2416            {
2417                Some(IndentSuggestion {
2418                    basis_row: prev_row,
2419                    delta: Ordering::Equal,
2420                    within_error,
2421                })
2422            } else if indent_from_prev_row {
2423                Some(IndentSuggestion {
2424                    basis_row: prev_row,
2425                    delta: Ordering::Greater,
2426                    within_error,
2427                })
2428            } else if outdent_to_row < prev_row {
2429                Some(IndentSuggestion {
2430                    basis_row: outdent_to_row,
2431                    delta: Ordering::Equal,
2432                    within_error,
2433                })
2434            } else if outdent_from_prev_row {
2435                Some(IndentSuggestion {
2436                    basis_row: prev_row,
2437                    delta: Ordering::Less,
2438                    within_error,
2439                })
2440            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
2441            {
2442                Some(IndentSuggestion {
2443                    basis_row: prev_row,
2444                    delta: Ordering::Equal,
2445                    within_error,
2446                })
2447            } else {
2448                None
2449            };
2450
2451            prev_row = row;
2452            prev_row_start = row_start;
2453            suggestion
2454        }))
2455    }
2456
2457    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2458        while row > 0 {
2459            row -= 1;
2460            if !self.is_line_blank(row) {
2461                return Some(row);
2462            }
2463        }
2464        None
2465    }
2466
2467    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
2468    /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
2469    /// returned in chunks where each chunk has a single syntax highlighting style and
2470    /// diagnostic status.
2471    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
2472        let range = range.start.to_offset(self)..range.end.to_offset(self);
2473
2474        let mut syntax = None;
2475        let mut diagnostic_endpoints = Vec::new();
2476        if language_aware {
2477            let captures = self.syntax.captures(range.clone(), &self.text, |grammar| {
2478                grammar.highlights_query.as_ref()
2479            });
2480            let highlight_maps = captures
2481                .grammars()
2482                .into_iter()
2483                .map(|grammar| grammar.highlight_map())
2484                .collect();
2485            syntax = Some((captures, highlight_maps));
2486            for entry in self.diagnostics_in_range::<_, usize>(range.clone(), false) {
2487                diagnostic_endpoints.push(DiagnosticEndpoint {
2488                    offset: entry.range.start,
2489                    is_start: true,
2490                    severity: entry.diagnostic.severity,
2491                    is_unnecessary: entry.diagnostic.is_unnecessary,
2492                });
2493                diagnostic_endpoints.push(DiagnosticEndpoint {
2494                    offset: entry.range.end,
2495                    is_start: false,
2496                    severity: entry.diagnostic.severity,
2497                    is_unnecessary: entry.diagnostic.is_unnecessary,
2498                });
2499            }
2500            diagnostic_endpoints
2501                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
2502        }
2503
2504        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostic_endpoints)
2505    }
2506
2507    /// Invokes the given callback for each line of text in the given range of the buffer.
2508    /// Uses callback to avoid allocating a string for each line.
2509    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
2510        let mut line = String::new();
2511        let mut row = range.start.row;
2512        for chunk in self
2513            .as_rope()
2514            .chunks_in_range(range.to_offset(self))
2515            .chain(["\n"])
2516        {
2517            for (newline_ix, text) in chunk.split('\n').enumerate() {
2518                if newline_ix > 0 {
2519                    callback(row, &line);
2520                    row += 1;
2521                    line.clear();
2522                }
2523                line.push_str(text);
2524            }
2525        }
2526    }
2527
2528    /// Iterates over every [`SyntaxLayer`] in the buffer.
2529    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
2530        self.syntax.layers_for_range(0..self.len(), &self.text)
2531    }
2532
2533    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
2534        let offset = position.to_offset(self);
2535        self.syntax
2536            .layers_for_range(offset..offset, &self.text)
2537            .filter(|l| l.node().end_byte() > offset)
2538            .last()
2539    }
2540
2541    /// Returns the main [Language]
2542    pub fn language(&self) -> Option<&Arc<Language>> {
2543        self.language.as_ref()
2544    }
2545
2546    /// Returns the [Language] at the given location.
2547    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
2548        self.syntax_layer_at(position)
2549            .map(|info| info.language)
2550            .or(self.language.as_ref())
2551    }
2552
2553    /// Returns the settings for the language at the given location.
2554    pub fn settings_at<'a, D: ToOffset>(
2555        &self,
2556        position: D,
2557        cx: &'a AppContext,
2558    ) -> &'a LanguageSettings {
2559        language_settings(self.language_at(position), self.file.as_ref(), cx)
2560    }
2561
2562    /// Returns the [LanguageScope] at the given location.
2563    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
2564        let offset = position.to_offset(self);
2565        let mut scope = None;
2566        let mut smallest_range: Option<Range<usize>> = None;
2567
2568        // Use the layer that has the smallest node intersecting the given point.
2569        for layer in self.syntax.layers_for_range(offset..offset, &self.text) {
2570            let mut cursor = layer.node().walk();
2571
2572            let mut range = None;
2573            loop {
2574                let child_range = cursor.node().byte_range();
2575                if !child_range.to_inclusive().contains(&offset) {
2576                    break;
2577                }
2578
2579                range = Some(child_range);
2580                if cursor.goto_first_child_for_byte(offset).is_none() {
2581                    break;
2582                }
2583            }
2584
2585            if let Some(range) = range {
2586                if smallest_range
2587                    .as_ref()
2588                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
2589                {
2590                    smallest_range = Some(range);
2591                    scope = Some(LanguageScope {
2592                        language: layer.language.clone(),
2593                        override_id: layer.override_id(offset, &self.text),
2594                    });
2595                }
2596            }
2597        }
2598
2599        scope.or_else(|| {
2600            self.language.clone().map(|language| LanguageScope {
2601                language,
2602                override_id: None,
2603            })
2604        })
2605    }
2606
2607    /// Returns a tuple of the range and character kind of the word
2608    /// surrounding the given position.
2609    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2610        let mut start = start.to_offset(self);
2611        let mut end = start;
2612        let mut next_chars = self.chars_at(start).peekable();
2613        let mut prev_chars = self.reversed_chars_at(start).peekable();
2614
2615        let scope = self.language_scope_at(start);
2616        let kind = |c| char_kind(&scope, c);
2617        let word_kind = cmp::max(
2618            prev_chars.peek().copied().map(kind),
2619            next_chars.peek().copied().map(kind),
2620        );
2621
2622        for ch in prev_chars {
2623            if Some(kind(ch)) == word_kind && ch != '\n' {
2624                start -= ch.len_utf8();
2625            } else {
2626                break;
2627            }
2628        }
2629
2630        for ch in next_chars {
2631            if Some(kind(ch)) == word_kind && ch != '\n' {
2632                end += ch.len_utf8();
2633            } else {
2634                break;
2635            }
2636        }
2637
2638        (start..end, word_kind)
2639    }
2640
2641    /// Returns the range for the closes syntax node enclosing the given range.
2642    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2643        let range = range.start.to_offset(self)..range.end.to_offset(self);
2644        let mut result: Option<Range<usize>> = None;
2645        'outer: for layer in self.syntax.layers_for_range(range.clone(), &self.text) {
2646            let mut cursor = layer.node().walk();
2647
2648            // Descend to the first leaf that touches the start of the range,
2649            // and if the range is non-empty, extends beyond the start.
2650            while cursor.goto_first_child_for_byte(range.start).is_some() {
2651                if !range.is_empty() && cursor.node().end_byte() == range.start {
2652                    cursor.goto_next_sibling();
2653                }
2654            }
2655
2656            // Ascend to the smallest ancestor that strictly contains the range.
2657            loop {
2658                let node_range = cursor.node().byte_range();
2659                if node_range.start <= range.start
2660                    && node_range.end >= range.end
2661                    && node_range.len() > range.len()
2662                {
2663                    break;
2664                }
2665                if !cursor.goto_parent() {
2666                    continue 'outer;
2667                }
2668            }
2669
2670            let left_node = cursor.node();
2671            let mut layer_result = left_node.byte_range();
2672
2673            // For an empty range, try to find another node immediately to the right of the range.
2674            if left_node.end_byte() == range.start {
2675                let mut right_node = None;
2676                while !cursor.goto_next_sibling() {
2677                    if !cursor.goto_parent() {
2678                        break;
2679                    }
2680                }
2681
2682                while cursor.node().start_byte() == range.start {
2683                    right_node = Some(cursor.node());
2684                    if !cursor.goto_first_child() {
2685                        break;
2686                    }
2687                }
2688
2689                // If there is a candidate node on both sides of the (empty) range, then
2690                // decide between the two by favoring a named node over an anonymous token.
2691                // If both nodes are the same in that regard, favor the right one.
2692                if let Some(right_node) = right_node {
2693                    if right_node.is_named() || !left_node.is_named() {
2694                        layer_result = right_node.byte_range();
2695                    }
2696                }
2697            }
2698
2699            if let Some(previous_result) = &result {
2700                if previous_result.len() < layer_result.len() {
2701                    continue;
2702                }
2703            }
2704            result = Some(layer_result);
2705        }
2706
2707        result
2708    }
2709
2710    /// Returns the outline for the buffer.
2711    ///
2712    /// This method allows passing an optional [SyntaxTheme] to
2713    /// syntax-highlight the returned symbols.
2714    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2715        self.outline_items_containing(0..self.len(), true, theme)
2716            .map(Outline::new)
2717    }
2718
2719    /// Returns all the symbols that contain the given position.
2720    ///
2721    /// This method allows passing an optional [SyntaxTheme] to
2722    /// syntax-highlight the returned symbols.
2723    pub fn symbols_containing<T: ToOffset>(
2724        &self,
2725        position: T,
2726        theme: Option<&SyntaxTheme>,
2727    ) -> Option<Vec<OutlineItem<Anchor>>> {
2728        let position = position.to_offset(self);
2729        let mut items = self.outline_items_containing(
2730            position.saturating_sub(1)..self.len().min(position + 1),
2731            false,
2732            theme,
2733        )?;
2734        let mut prev_depth = None;
2735        items.retain(|item| {
2736            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
2737            prev_depth = Some(item.depth);
2738            result
2739        });
2740        Some(items)
2741    }
2742
2743    pub fn outline_items_containing<T: ToOffset>(
2744        &self,
2745        range: Range<T>,
2746        include_extra_context: bool,
2747        theme: Option<&SyntaxTheme>,
2748    ) -> Option<Vec<OutlineItem<Anchor>>> {
2749        let range = range.to_offset(self);
2750        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2751            grammar.outline_config.as_ref().map(|c| &c.query)
2752        });
2753        let configs = matches
2754            .grammars()
2755            .iter()
2756            .map(|g| g.outline_config.as_ref().unwrap())
2757            .collect::<Vec<_>>();
2758
2759        let mut stack = Vec::<Range<usize>>::new();
2760        let mut items = Vec::new();
2761        while let Some(mat) = matches.peek() {
2762            let config = &configs[mat.grammar_index];
2763            let item_node = mat.captures.iter().find_map(|cap| {
2764                if cap.index == config.item_capture_ix {
2765                    Some(cap.node)
2766                } else {
2767                    None
2768                }
2769            })?;
2770
2771            let item_range = item_node.byte_range();
2772            if item_range.end < range.start || item_range.start > range.end {
2773                matches.advance();
2774                continue;
2775            }
2776
2777            let mut buffer_ranges = Vec::new();
2778            for capture in mat.captures {
2779                let node_is_name;
2780                if capture.index == config.name_capture_ix {
2781                    node_is_name = true;
2782                } else if Some(capture.index) == config.context_capture_ix
2783                    || (Some(capture.index) == config.extra_context_capture_ix
2784                        && include_extra_context)
2785                {
2786                    node_is_name = false;
2787                } else {
2788                    continue;
2789                }
2790
2791                let mut range = capture.node.start_byte()..capture.node.end_byte();
2792                let start = capture.node.start_position();
2793                if capture.node.end_position().row > start.row {
2794                    range.end =
2795                        range.start + self.line_len(start.row as u32) as usize - start.column;
2796                }
2797
2798                if !range.is_empty() {
2799                    buffer_ranges.push((range, node_is_name));
2800                }
2801            }
2802
2803            if buffer_ranges.is_empty() {
2804                matches.advance();
2805                continue;
2806            }
2807
2808            let mut text = String::new();
2809            let mut highlight_ranges = Vec::new();
2810            let mut name_ranges = Vec::new();
2811            let mut chunks = self.chunks(
2812                buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
2813                true,
2814            );
2815            let mut last_buffer_range_end = 0;
2816            for (buffer_range, is_name) in buffer_ranges {
2817                if !text.is_empty() && buffer_range.start > last_buffer_range_end {
2818                    text.push(' ');
2819                }
2820                last_buffer_range_end = buffer_range.end;
2821                if is_name {
2822                    let mut start = text.len();
2823                    let end = start + buffer_range.len();
2824
2825                    // When multiple names are captured, then the matcheable text
2826                    // includes the whitespace in between the names.
2827                    if !name_ranges.is_empty() {
2828                        start -= 1;
2829                    }
2830
2831                    name_ranges.push(start..end);
2832                }
2833
2834                let mut offset = buffer_range.start;
2835                chunks.seek(offset);
2836                for mut chunk in chunks.by_ref() {
2837                    if chunk.text.len() > buffer_range.end - offset {
2838                        chunk.text = &chunk.text[0..(buffer_range.end - offset)];
2839                        offset = buffer_range.end;
2840                    } else {
2841                        offset += chunk.text.len();
2842                    }
2843                    let style = chunk
2844                        .syntax_highlight_id
2845                        .zip(theme)
2846                        .and_then(|(highlight, theme)| highlight.style(theme));
2847                    if let Some(style) = style {
2848                        let start = text.len();
2849                        let end = start + chunk.text.len();
2850                        highlight_ranges.push((start..end, style));
2851                    }
2852                    text.push_str(chunk.text);
2853                    if offset >= buffer_range.end {
2854                        break;
2855                    }
2856                }
2857            }
2858
2859            matches.advance();
2860            while stack.last().map_or(false, |prev_range| {
2861                prev_range.start > item_range.start || prev_range.end < item_range.end
2862            }) {
2863                stack.pop();
2864            }
2865            stack.push(item_range.clone());
2866
2867            items.push(OutlineItem {
2868                depth: stack.len() - 1,
2869                range: self.anchor_after(item_range.start)..self.anchor_before(item_range.end),
2870                text,
2871                highlight_ranges,
2872                name_ranges,
2873            })
2874        }
2875        Some(items)
2876    }
2877
2878    /// For each grammar in the language, runs the provided
2879    /// [tree_sitter::Query] against the given range.
2880    pub fn matches(
2881        &self,
2882        range: Range<usize>,
2883        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
2884    ) -> SyntaxMapMatches {
2885        self.syntax.matches(range, self, query)
2886    }
2887
2888    /// Returns bracket range pairs overlapping or adjacent to `range`
2889    pub fn bracket_ranges<T: ToOffset>(
2890        &self,
2891        range: Range<T>,
2892    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
2893        // Find bracket pairs that *inclusively* contain the given range.
2894        let range = range.start.to_offset(self).saturating_sub(1)
2895            ..self.len().min(range.end.to_offset(self) + 1);
2896
2897        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2898            grammar.brackets_config.as_ref().map(|c| &c.query)
2899        });
2900        let configs = matches
2901            .grammars()
2902            .iter()
2903            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
2904            .collect::<Vec<_>>();
2905
2906        iter::from_fn(move || {
2907            while let Some(mat) = matches.peek() {
2908                let mut open = None;
2909                let mut close = None;
2910                let config = &configs[mat.grammar_index];
2911                for capture in mat.captures {
2912                    if capture.index == config.open_capture_ix {
2913                        open = Some(capture.node.byte_range());
2914                    } else if capture.index == config.close_capture_ix {
2915                        close = Some(capture.node.byte_range());
2916                    }
2917                }
2918
2919                matches.advance();
2920
2921                let Some((open, close)) = open.zip(close) else {
2922                    continue;
2923                };
2924
2925                let bracket_range = open.start..=close.end;
2926                if !bracket_range.overlaps(&range) {
2927                    continue;
2928                }
2929
2930                return Some((open, close));
2931            }
2932            None
2933        })
2934    }
2935
2936    /// Returns enclosing bracket ranges containing the given range
2937    pub fn enclosing_bracket_ranges<T: ToOffset>(
2938        &self,
2939        range: Range<T>,
2940    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
2941        let range = range.start.to_offset(self)..range.end.to_offset(self);
2942
2943        self.bracket_ranges(range.clone())
2944            .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
2945    }
2946
2947    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
2948    ///
2949    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
2950    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
2951        &self,
2952        range: Range<T>,
2953        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
2954    ) -> Option<(Range<usize>, Range<usize>)> {
2955        let range = range.start.to_offset(self)..range.end.to_offset(self);
2956
2957        // Get the ranges of the innermost pair of brackets.
2958        let mut result: Option<(Range<usize>, Range<usize>)> = None;
2959
2960        for (open, close) in self.enclosing_bracket_ranges(range.clone()) {
2961            if let Some(range_filter) = range_filter {
2962                if !range_filter(open.clone(), close.clone()) {
2963                    continue;
2964                }
2965            }
2966
2967            let len = close.end - open.start;
2968
2969            if let Some((existing_open, existing_close)) = &result {
2970                let existing_len = existing_close.end - existing_open.start;
2971                if len > existing_len {
2972                    continue;
2973                }
2974            }
2975
2976            result = Some((open, close));
2977        }
2978
2979        result
2980    }
2981
2982    /// Returns anchor ranges for any matches of the redaction query.
2983    /// The buffer can be associated with multiple languages, and the redaction query associated with each
2984    /// will be run on the relevant section of the buffer.
2985    pub fn redacted_ranges<T: ToOffset>(
2986        &self,
2987        range: Range<T>,
2988    ) -> impl Iterator<Item = Range<usize>> + '_ {
2989        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
2990        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
2991            grammar
2992                .redactions_config
2993                .as_ref()
2994                .map(|config| &config.query)
2995        });
2996
2997        let configs = syntax_matches
2998            .grammars()
2999            .iter()
3000            .map(|grammar| grammar.redactions_config.as_ref())
3001            .collect::<Vec<_>>();
3002
3003        iter::from_fn(move || {
3004            let redacted_range = syntax_matches
3005                .peek()
3006                .and_then(|mat| {
3007                    configs[mat.grammar_index].and_then(|config| {
3008                        mat.captures
3009                            .iter()
3010                            .find(|capture| capture.index == config.redaction_capture_ix)
3011                    })
3012                })
3013                .map(|mat| mat.node.byte_range());
3014            syntax_matches.advance();
3015            redacted_range
3016        })
3017    }
3018
3019    pub fn runnable_ranges(
3020        &self,
3021        range: Range<Anchor>,
3022    ) -> impl Iterator<Item = RunnableRange> + '_ {
3023        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3024
3025        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3026            grammar.runnable_config.as_ref().map(|config| &config.query)
3027        });
3028
3029        let test_configs = syntax_matches
3030            .grammars()
3031            .iter()
3032            .map(|grammar| grammar.runnable_config.as_ref())
3033            .collect::<Vec<_>>();
3034
3035        iter::from_fn(move || loop {
3036            let mat = syntax_matches.peek()?;
3037
3038            let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3039                let mut run_range = None;
3040                let full_range = mat.captures.iter().fold(
3041                    Range {
3042                        start: usize::MAX,
3043                        end: 0,
3044                    },
3045                    |mut acc, next| {
3046                        let byte_range = next.node.byte_range();
3047                        if acc.start > byte_range.start {
3048                            acc.start = byte_range.start;
3049                        }
3050                        if acc.end < byte_range.end {
3051                            acc.end = byte_range.end;
3052                        }
3053                        acc
3054                    },
3055                );
3056                if full_range.start > full_range.end {
3057                    // We did not find a full spanning range of this match.
3058                    return None;
3059                }
3060                let extra_captures: SmallVec<[_; 1]> =
3061                    SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3062                        test_configs
3063                            .extra_captures
3064                            .get(capture.index as usize)
3065                            .cloned()
3066                            .and_then(|tag_name| match tag_name {
3067                                RunnableCapture::Named(name) => {
3068                                    Some((capture.node.byte_range(), name))
3069                                }
3070                                RunnableCapture::Run => {
3071                                    let _ = run_range.insert(capture.node.byte_range());
3072                                    None
3073                                }
3074                            })
3075                    }));
3076                let run_range = run_range?;
3077                let tags = test_configs
3078                    .query
3079                    .property_settings(mat.pattern_index)
3080                    .iter()
3081                    .filter_map(|property| {
3082                        if *property.key == *"tag" {
3083                            property
3084                                .value
3085                                .as_ref()
3086                                .map(|value| RunnableTag(value.to_string().into()))
3087                        } else {
3088                            None
3089                        }
3090                    })
3091                    .collect();
3092                let extra_captures = extra_captures
3093                    .into_iter()
3094                    .map(|(range, name)| {
3095                        (
3096                            name.to_string(),
3097                            self.text_for_range(range.clone()).collect::<String>(),
3098                        )
3099                    })
3100                    .collect();
3101                // All tags should have the same range.
3102                Some(RunnableRange {
3103                    run_range,
3104                    full_range,
3105                    runnable: Runnable {
3106                        tags,
3107                        language: mat.language,
3108                        buffer: self.remote_id(),
3109                    },
3110                    extra_captures,
3111                    buffer_id: self.remote_id(),
3112                })
3113            });
3114
3115            syntax_matches.advance();
3116            if test_range.is_some() {
3117                // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
3118                // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
3119                return test_range;
3120            }
3121        })
3122    }
3123
3124    pub fn indent_guides_in_range(
3125        &self,
3126        range: Range<Anchor>,
3127        ignore_disabled_for_language: bool,
3128        cx: &AppContext,
3129    ) -> Vec<IndentGuide> {
3130        let language_settings = language_settings(self.language(), self.file.as_ref(), cx);
3131        let settings = language_settings.indent_guides;
3132        if !ignore_disabled_for_language && !settings.enabled {
3133            return Vec::new();
3134        }
3135        let tab_size = language_settings.tab_size.get() as u32;
3136
3137        let start_row = range.start.to_point(self).row;
3138        let end_row = range.end.to_point(self).row;
3139        let row_range = start_row..end_row + 1;
3140
3141        let mut row_indents = self.line_indents_in_row_range(row_range.clone());
3142
3143        let mut result_vec = Vec::new();
3144        let mut indent_stack = SmallVec::<[IndentGuide; 8]>::new();
3145
3146        while let Some((first_row, mut line_indent)) = row_indents.next() {
3147            let current_depth = indent_stack.len() as u32;
3148
3149            // When encountering empty, continue until found useful line indent
3150            // then add to the indent stack with the depth found
3151            let mut found_indent = false;
3152            let mut last_row = first_row;
3153            if line_indent.is_line_empty() {
3154                let mut trailing_row = end_row;
3155                while !found_indent {
3156                    let (target_row, new_line_indent) =
3157                        if let Some(display_row) = row_indents.next() {
3158                            display_row
3159                        } else {
3160                            // This means we reached the end of the given range and found empty lines at the end.
3161                            // We need to traverse further until we find a non-empty line to know if we need to add
3162                            // an indent guide for the last visible indent.
3163                            trailing_row += 1;
3164
3165                            const TRAILING_ROW_SEARCH_LIMIT: u32 = 25;
3166                            if trailing_row > self.max_point().row
3167                                || trailing_row > end_row + TRAILING_ROW_SEARCH_LIMIT
3168                            {
3169                                break;
3170                            }
3171                            let new_line_indent = self.line_indent_for_row(trailing_row);
3172                            (trailing_row, new_line_indent)
3173                        };
3174
3175                    if new_line_indent.is_line_empty() {
3176                        continue;
3177                    }
3178                    last_row = target_row.min(end_row);
3179                    line_indent = new_line_indent;
3180                    found_indent = true;
3181                    break;
3182                }
3183            } else {
3184                found_indent = true
3185            }
3186
3187            let depth = if found_indent {
3188                line_indent.len(tab_size) / tab_size
3189                    + ((line_indent.len(tab_size) % tab_size) > 0) as u32
3190            } else {
3191                current_depth
3192            };
3193
3194            if depth < current_depth {
3195                for _ in 0..(current_depth - depth) {
3196                    let mut indent = indent_stack.pop().unwrap();
3197                    if last_row != first_row {
3198                        // In this case, we landed on an empty row, had to seek forward,
3199                        // and discovered that the indent we where on is ending.
3200                        // This means that the last display row must
3201                        // be on line that ends this indent range, so we
3202                        // should display the range up to the first non-empty line
3203                        indent.end_row = first_row.saturating_sub(1);
3204                    }
3205
3206                    result_vec.push(indent)
3207                }
3208            } else if depth > current_depth {
3209                for next_depth in current_depth..depth {
3210                    indent_stack.push(IndentGuide {
3211                        buffer_id: self.remote_id(),
3212                        start_row: first_row,
3213                        end_row: last_row,
3214                        depth: next_depth,
3215                        tab_size,
3216                        settings,
3217                    });
3218                }
3219            }
3220
3221            for indent in indent_stack.iter_mut() {
3222                indent.end_row = last_row;
3223            }
3224        }
3225
3226        result_vec.extend(indent_stack);
3227
3228        result_vec
3229    }
3230
3231    pub async fn enclosing_indent(
3232        &self,
3233        mut buffer_row: BufferRow,
3234    ) -> Option<(Range<BufferRow>, LineIndent)> {
3235        let max_row = self.max_point().row;
3236        if buffer_row >= max_row {
3237            return None;
3238        }
3239
3240        let mut target_indent = self.line_indent_for_row(buffer_row);
3241
3242        // If the current row is at the start of an indented block, we want to return this
3243        // block as the enclosing indent.
3244        if !target_indent.is_line_empty() && buffer_row < max_row {
3245            let next_line_indent = self.line_indent_for_row(buffer_row + 1);
3246            if !next_line_indent.is_line_empty()
3247                && target_indent.raw_len() < next_line_indent.raw_len()
3248            {
3249                target_indent = next_line_indent;
3250                buffer_row += 1;
3251            }
3252        }
3253
3254        const SEARCH_ROW_LIMIT: u32 = 25000;
3255        const SEARCH_WHITESPACE_ROW_LIMIT: u32 = 2500;
3256        const YIELD_INTERVAL: u32 = 100;
3257
3258        let mut accessed_row_counter = 0;
3259
3260        // If there is a blank line at the current row, search for the next non indented lines
3261        if target_indent.is_line_empty() {
3262            let start = buffer_row.saturating_sub(SEARCH_WHITESPACE_ROW_LIMIT);
3263            let end = (max_row + 1).min(buffer_row + SEARCH_WHITESPACE_ROW_LIMIT);
3264
3265            let mut non_empty_line_above = None;
3266            for (row, indent) in self
3267                .text
3268                .reversed_line_indents_in_row_range(start..buffer_row)
3269            {
3270                accessed_row_counter += 1;
3271                if accessed_row_counter == YIELD_INTERVAL {
3272                    accessed_row_counter = 0;
3273                    yield_now().await;
3274                }
3275                if !indent.is_line_empty() {
3276                    non_empty_line_above = Some((row, indent));
3277                    break;
3278                }
3279            }
3280
3281            let mut non_empty_line_below = None;
3282            for (row, indent) in self.text.line_indents_in_row_range((buffer_row + 1)..end) {
3283                accessed_row_counter += 1;
3284                if accessed_row_counter == YIELD_INTERVAL {
3285                    accessed_row_counter = 0;
3286                    yield_now().await;
3287                }
3288                if !indent.is_line_empty() {
3289                    non_empty_line_below = Some((row, indent));
3290                    break;
3291                }
3292            }
3293
3294            let (row, indent) = match (non_empty_line_above, non_empty_line_below) {
3295                (Some((above_row, above_indent)), Some((below_row, below_indent))) => {
3296                    if above_indent.raw_len() >= below_indent.raw_len() {
3297                        (above_row, above_indent)
3298                    } else {
3299                        (below_row, below_indent)
3300                    }
3301                }
3302                (Some(above), None) => above,
3303                (None, Some(below)) => below,
3304                _ => return None,
3305            };
3306
3307            target_indent = indent;
3308            buffer_row = row;
3309        }
3310
3311        let start = buffer_row.saturating_sub(SEARCH_ROW_LIMIT);
3312        let end = (max_row + 1).min(buffer_row + SEARCH_ROW_LIMIT);
3313
3314        let mut start_indent = None;
3315        for (row, indent) in self
3316            .text
3317            .reversed_line_indents_in_row_range(start..buffer_row)
3318        {
3319            accessed_row_counter += 1;
3320            if accessed_row_counter == YIELD_INTERVAL {
3321                accessed_row_counter = 0;
3322                yield_now().await;
3323            }
3324            if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
3325                start_indent = Some((row, indent));
3326                break;
3327            }
3328        }
3329        let (start_row, start_indent_size) = start_indent?;
3330
3331        let mut end_indent = (end, None);
3332        for (row, indent) in self.text.line_indents_in_row_range((buffer_row + 1)..end) {
3333            accessed_row_counter += 1;
3334            if accessed_row_counter == YIELD_INTERVAL {
3335                accessed_row_counter = 0;
3336                yield_now().await;
3337            }
3338            if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
3339                end_indent = (row.saturating_sub(1), Some(indent));
3340                break;
3341            }
3342        }
3343        let (end_row, end_indent_size) = end_indent;
3344
3345        let indent = if let Some(end_indent_size) = end_indent_size {
3346            if start_indent_size.raw_len() > end_indent_size.raw_len() {
3347                start_indent_size
3348            } else {
3349                end_indent_size
3350            }
3351        } else {
3352            start_indent_size
3353        };
3354
3355        Some((start_row..end_row, indent))
3356    }
3357
3358    /// Returns selections for remote peers intersecting the given range.
3359    #[allow(clippy::type_complexity)]
3360    pub fn selections_in_range(
3361        &self,
3362        range: Range<Anchor>,
3363        include_local: bool,
3364    ) -> impl Iterator<
3365        Item = (
3366            ReplicaId,
3367            bool,
3368            CursorShape,
3369            impl Iterator<Item = &Selection<Anchor>> + '_,
3370        ),
3371    > + '_ {
3372        self.remote_selections
3373            .iter()
3374            .filter(move |(replica_id, set)| {
3375                (include_local || **replica_id != self.text.replica_id())
3376                    && !set.selections.is_empty()
3377            })
3378            .map(move |(replica_id, set)| {
3379                let start_ix = match set.selections.binary_search_by(|probe| {
3380                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
3381                }) {
3382                    Ok(ix) | Err(ix) => ix,
3383                };
3384                let end_ix = match set.selections.binary_search_by(|probe| {
3385                    probe.start.cmp(&range.end, self).then(Ordering::Less)
3386                }) {
3387                    Ok(ix) | Err(ix) => ix,
3388                };
3389
3390                (
3391                    *replica_id,
3392                    set.line_mode,
3393                    set.cursor_shape,
3394                    set.selections[start_ix..end_ix].iter(),
3395                )
3396            })
3397    }
3398
3399    /// Whether the buffer contains any git changes.
3400    pub fn has_git_diff(&self) -> bool {
3401        !self.git_diff.is_empty()
3402    }
3403
3404    /// Returns all the Git diff hunks intersecting the given
3405    /// row range.
3406    pub fn git_diff_hunks_in_row_range(
3407        &self,
3408        range: Range<BufferRow>,
3409    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3410        self.git_diff.hunks_in_row_range(range, self)
3411    }
3412
3413    /// Returns all the Git diff hunks intersecting the given
3414    /// range.
3415    pub fn git_diff_hunks_intersecting_range(
3416        &self,
3417        range: Range<Anchor>,
3418    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3419        self.git_diff.hunks_intersecting_range(range, self)
3420    }
3421
3422    /// Returns all the Git diff hunks intersecting the given
3423    /// range, in reverse order.
3424    pub fn git_diff_hunks_intersecting_range_rev(
3425        &self,
3426        range: Range<Anchor>,
3427    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3428        self.git_diff.hunks_intersecting_range_rev(range, self)
3429    }
3430
3431    /// Returns if the buffer contains any diagnostics.
3432    pub fn has_diagnostics(&self) -> bool {
3433        !self.diagnostics.is_empty()
3434    }
3435
3436    /// Returns all the diagnostics intersecting the given range.
3437    pub fn diagnostics_in_range<'a, T, O>(
3438        &'a self,
3439        search_range: Range<T>,
3440        reversed: bool,
3441    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3442    where
3443        T: 'a + Clone + ToOffset,
3444        O: 'a + FromAnchor + Ord,
3445    {
3446        let mut iterators: Vec<_> = self
3447            .diagnostics
3448            .iter()
3449            .map(|(_, collection)| {
3450                collection
3451                    .range::<T, O>(search_range.clone(), self, true, reversed)
3452                    .peekable()
3453            })
3454            .collect();
3455
3456        std::iter::from_fn(move || {
3457            let (next_ix, _) = iterators
3458                .iter_mut()
3459                .enumerate()
3460                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
3461                .min_by(|(_, a), (_, b)| {
3462                    let cmp = a
3463                        .range
3464                        .start
3465                        .cmp(&b.range.start)
3466                        // when range is equal, sort by diagnostic severity
3467                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
3468                        // and stabilize order with group_id
3469                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
3470                    if reversed {
3471                        cmp.reverse()
3472                    } else {
3473                        cmp
3474                    }
3475                })?;
3476            iterators[next_ix].next()
3477        })
3478    }
3479
3480    /// Returns all the diagnostic groups associated with the given
3481    /// language server id. If no language server id is provided,
3482    /// all diagnostics groups are returned.
3483    pub fn diagnostic_groups(
3484        &self,
3485        language_server_id: Option<LanguageServerId>,
3486    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
3487        let mut groups = Vec::new();
3488
3489        if let Some(language_server_id) = language_server_id {
3490            if let Ok(ix) = self
3491                .diagnostics
3492                .binary_search_by_key(&language_server_id, |e| e.0)
3493            {
3494                self.diagnostics[ix]
3495                    .1
3496                    .groups(language_server_id, &mut groups, self);
3497            }
3498        } else {
3499            for (language_server_id, diagnostics) in self.diagnostics.iter() {
3500                diagnostics.groups(*language_server_id, &mut groups, self);
3501            }
3502        }
3503
3504        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
3505            let a_start = &group_a.entries[group_a.primary_ix].range.start;
3506            let b_start = &group_b.entries[group_b.primary_ix].range.start;
3507            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
3508        });
3509
3510        groups
3511    }
3512
3513    /// Returns an iterator over the diagnostics for the given group.
3514    pub fn diagnostic_group<'a, O>(
3515        &'a self,
3516        group_id: usize,
3517    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3518    where
3519        O: 'a + FromAnchor,
3520    {
3521        self.diagnostics
3522            .iter()
3523            .flat_map(move |(_, set)| set.group(group_id, self))
3524    }
3525
3526    /// The number of times diagnostics were updated.
3527    pub fn diagnostics_update_count(&self) -> usize {
3528        self.diagnostics_update_count
3529    }
3530
3531    /// The number of times the buffer was parsed.
3532    pub fn parse_count(&self) -> usize {
3533        self.parse_count
3534    }
3535
3536    /// The number of times selections were updated.
3537    pub fn selections_update_count(&self) -> usize {
3538        self.selections_update_count
3539    }
3540
3541    /// Returns a snapshot of underlying file.
3542    pub fn file(&self) -> Option<&Arc<dyn File>> {
3543        self.file.as_ref()
3544    }
3545
3546    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
3547    pub fn resolve_file_path(&self, cx: &AppContext, include_root: bool) -> Option<PathBuf> {
3548        if let Some(file) = self.file() {
3549            if file.path().file_name().is_none() || include_root {
3550                Some(file.full_path(cx))
3551            } else {
3552                Some(file.path().to_path_buf())
3553            }
3554        } else {
3555            None
3556        }
3557    }
3558
3559    /// The number of times the underlying file was updated.
3560    pub fn file_update_count(&self) -> usize {
3561        self.file_update_count
3562    }
3563
3564    /// The number of times the git diff status was updated.
3565    pub fn git_diff_update_count(&self) -> usize {
3566        self.git_diff_update_count
3567    }
3568}
3569
3570fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
3571    indent_size_for_text(text.chars_at(Point::new(row, 0)))
3572}
3573
3574fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
3575    let mut result = IndentSize::spaces(0);
3576    for c in text {
3577        let kind = match c {
3578            ' ' => IndentKind::Space,
3579            '\t' => IndentKind::Tab,
3580            _ => break,
3581        };
3582        if result.len == 0 {
3583            result.kind = kind;
3584        }
3585        result.len += 1;
3586    }
3587    result
3588}
3589
3590impl Clone for BufferSnapshot {
3591    fn clone(&self) -> Self {
3592        Self {
3593            text: self.text.clone(),
3594            git_diff: self.git_diff.clone(),
3595            syntax: self.syntax.clone(),
3596            file: self.file.clone(),
3597            remote_selections: self.remote_selections.clone(),
3598            diagnostics: self.diagnostics.clone(),
3599            selections_update_count: self.selections_update_count,
3600            diagnostics_update_count: self.diagnostics_update_count,
3601            file_update_count: self.file_update_count,
3602            git_diff_update_count: self.git_diff_update_count,
3603            language: self.language.clone(),
3604            parse_count: self.parse_count,
3605        }
3606    }
3607}
3608
3609impl Deref for BufferSnapshot {
3610    type Target = text::BufferSnapshot;
3611
3612    fn deref(&self) -> &Self::Target {
3613        &self.text
3614    }
3615}
3616
3617unsafe impl<'a> Send for BufferChunks<'a> {}
3618
3619impl<'a> BufferChunks<'a> {
3620    pub(crate) fn new(
3621        text: &'a Rope,
3622        range: Range<usize>,
3623        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
3624        diagnostic_endpoints: Vec<DiagnosticEndpoint>,
3625    ) -> Self {
3626        let mut highlights = None;
3627        if let Some((captures, highlight_maps)) = syntax {
3628            highlights = Some(BufferChunkHighlights {
3629                captures,
3630                next_capture: None,
3631                stack: Default::default(),
3632                highlight_maps,
3633            })
3634        }
3635
3636        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
3637        let chunks = text.chunks_in_range(range.clone());
3638
3639        BufferChunks {
3640            range,
3641            chunks,
3642            diagnostic_endpoints,
3643            error_depth: 0,
3644            warning_depth: 0,
3645            information_depth: 0,
3646            hint_depth: 0,
3647            unnecessary_depth: 0,
3648            highlights,
3649        }
3650    }
3651
3652    /// Seeks to the given byte offset in the buffer.
3653    pub fn seek(&mut self, offset: usize) {
3654        self.range.start = offset;
3655        self.chunks.seek(self.range.start);
3656        if let Some(highlights) = self.highlights.as_mut() {
3657            highlights
3658                .stack
3659                .retain(|(end_offset, _)| *end_offset > offset);
3660            if let Some(capture) = &highlights.next_capture {
3661                if offset >= capture.node.start_byte() {
3662                    let next_capture_end = capture.node.end_byte();
3663                    if offset < next_capture_end {
3664                        highlights.stack.push((
3665                            next_capture_end,
3666                            highlights.highlight_maps[capture.grammar_index].get(capture.index),
3667                        ));
3668                    }
3669                    highlights.next_capture.take();
3670                }
3671            }
3672            highlights.captures.set_byte_range(self.range.clone());
3673        }
3674    }
3675
3676    /// The current byte offset in the buffer.
3677    pub fn offset(&self) -> usize {
3678        self.range.start
3679    }
3680
3681    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
3682        let depth = match endpoint.severity {
3683            DiagnosticSeverity::ERROR => &mut self.error_depth,
3684            DiagnosticSeverity::WARNING => &mut self.warning_depth,
3685            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
3686            DiagnosticSeverity::HINT => &mut self.hint_depth,
3687            _ => return,
3688        };
3689        if endpoint.is_start {
3690            *depth += 1;
3691        } else {
3692            *depth -= 1;
3693        }
3694
3695        if endpoint.is_unnecessary {
3696            if endpoint.is_start {
3697                self.unnecessary_depth += 1;
3698            } else {
3699                self.unnecessary_depth -= 1;
3700            }
3701        }
3702    }
3703
3704    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
3705        if self.error_depth > 0 {
3706            Some(DiagnosticSeverity::ERROR)
3707        } else if self.warning_depth > 0 {
3708            Some(DiagnosticSeverity::WARNING)
3709        } else if self.information_depth > 0 {
3710            Some(DiagnosticSeverity::INFORMATION)
3711        } else if self.hint_depth > 0 {
3712            Some(DiagnosticSeverity::HINT)
3713        } else {
3714            None
3715        }
3716    }
3717
3718    fn current_code_is_unnecessary(&self) -> bool {
3719        self.unnecessary_depth > 0
3720    }
3721}
3722
3723impl<'a> Iterator for BufferChunks<'a> {
3724    type Item = Chunk<'a>;
3725
3726    fn next(&mut self) -> Option<Self::Item> {
3727        let mut next_capture_start = usize::MAX;
3728        let mut next_diagnostic_endpoint = usize::MAX;
3729
3730        if let Some(highlights) = self.highlights.as_mut() {
3731            while let Some((parent_capture_end, _)) = highlights.stack.last() {
3732                if *parent_capture_end <= self.range.start {
3733                    highlights.stack.pop();
3734                } else {
3735                    break;
3736                }
3737            }
3738
3739            if highlights.next_capture.is_none() {
3740                highlights.next_capture = highlights.captures.next();
3741            }
3742
3743            while let Some(capture) = highlights.next_capture.as_ref() {
3744                if self.range.start < capture.node.start_byte() {
3745                    next_capture_start = capture.node.start_byte();
3746                    break;
3747                } else {
3748                    let highlight_id =
3749                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
3750                    highlights
3751                        .stack
3752                        .push((capture.node.end_byte(), highlight_id));
3753                    highlights.next_capture = highlights.captures.next();
3754                }
3755            }
3756        }
3757
3758        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
3759            if endpoint.offset <= self.range.start {
3760                self.update_diagnostic_depths(endpoint);
3761                self.diagnostic_endpoints.next();
3762            } else {
3763                next_diagnostic_endpoint = endpoint.offset;
3764                break;
3765            }
3766        }
3767
3768        if let Some(chunk) = self.chunks.peek() {
3769            let chunk_start = self.range.start;
3770            let mut chunk_end = (self.chunks.offset() + chunk.len())
3771                .min(next_capture_start)
3772                .min(next_diagnostic_endpoint);
3773            let mut highlight_id = None;
3774            if let Some(highlights) = self.highlights.as_ref() {
3775                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
3776                    chunk_end = chunk_end.min(*parent_capture_end);
3777                    highlight_id = Some(*parent_highlight_id);
3778                }
3779            }
3780
3781            let slice =
3782                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
3783            self.range.start = chunk_end;
3784            if self.range.start == self.chunks.offset() + chunk.len() {
3785                self.chunks.next().unwrap();
3786            }
3787
3788            Some(Chunk {
3789                text: slice,
3790                syntax_highlight_id: highlight_id,
3791                diagnostic_severity: self.current_diagnostic_severity(),
3792                is_unnecessary: self.current_code_is_unnecessary(),
3793                ..Default::default()
3794            })
3795        } else {
3796            None
3797        }
3798    }
3799}
3800
3801impl operation_queue::Operation for Operation {
3802    fn lamport_timestamp(&self) -> clock::Lamport {
3803        match self {
3804            Operation::Buffer(_) => {
3805                unreachable!("buffer operations should never be deferred at this layer")
3806            }
3807            Operation::UpdateDiagnostics {
3808                lamport_timestamp, ..
3809            }
3810            | Operation::UpdateSelections {
3811                lamport_timestamp, ..
3812            }
3813            | Operation::UpdateCompletionTriggers {
3814                lamport_timestamp, ..
3815            } => *lamport_timestamp,
3816        }
3817    }
3818}
3819
3820impl Default for Diagnostic {
3821    fn default() -> Self {
3822        Self {
3823            source: Default::default(),
3824            code: None,
3825            severity: DiagnosticSeverity::ERROR,
3826            message: Default::default(),
3827            group_id: 0,
3828            is_primary: false,
3829            is_disk_based: false,
3830            is_unnecessary: false,
3831        }
3832    }
3833}
3834
3835impl IndentSize {
3836    /// Returns an [IndentSize] representing the given spaces.
3837    pub fn spaces(len: u32) -> Self {
3838        Self {
3839            len,
3840            kind: IndentKind::Space,
3841        }
3842    }
3843
3844    /// Returns an [IndentSize] representing a tab.
3845    pub fn tab() -> Self {
3846        Self {
3847            len: 1,
3848            kind: IndentKind::Tab,
3849        }
3850    }
3851
3852    /// An iterator over the characters represented by this [IndentSize].
3853    pub fn chars(&self) -> impl Iterator<Item = char> {
3854        iter::repeat(self.char()).take(self.len as usize)
3855    }
3856
3857    /// The character representation of this [IndentSize].
3858    pub fn char(&self) -> char {
3859        match self.kind {
3860            IndentKind::Space => ' ',
3861            IndentKind::Tab => '\t',
3862        }
3863    }
3864
3865    /// Consumes the current [IndentSize] and returns a new one that has
3866    /// been shrunk or enlarged by the given size along the given direction.
3867    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
3868        match direction {
3869            Ordering::Less => {
3870                if self.kind == size.kind && self.len >= size.len {
3871                    self.len -= size.len;
3872                }
3873            }
3874            Ordering::Equal => {}
3875            Ordering::Greater => {
3876                if self.len == 0 {
3877                    self = size;
3878                } else if self.kind == size.kind {
3879                    self.len += size.len;
3880                }
3881            }
3882        }
3883        self
3884    }
3885}
3886
3887#[cfg(any(test, feature = "test-support"))]
3888pub struct TestFile {
3889    pub path: Arc<Path>,
3890    pub root_name: String,
3891}
3892
3893#[cfg(any(test, feature = "test-support"))]
3894impl File for TestFile {
3895    fn path(&self) -> &Arc<Path> {
3896        &self.path
3897    }
3898
3899    fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
3900        PathBuf::from(&self.root_name).join(self.path.as_ref())
3901    }
3902
3903    fn as_local(&self) -> Option<&dyn LocalFile> {
3904        None
3905    }
3906
3907    fn mtime(&self) -> Option<SystemTime> {
3908        unimplemented!()
3909    }
3910
3911    fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
3912        self.path().file_name().unwrap_or(self.root_name.as_ref())
3913    }
3914
3915    fn worktree_id(&self) -> usize {
3916        0
3917    }
3918
3919    fn is_deleted(&self) -> bool {
3920        unimplemented!()
3921    }
3922
3923    fn as_any(&self) -> &dyn std::any::Any {
3924        unimplemented!()
3925    }
3926
3927    fn to_proto(&self) -> rpc::proto::File {
3928        unimplemented!()
3929    }
3930
3931    fn is_private(&self) -> bool {
3932        false
3933    }
3934}
3935
3936pub(crate) fn contiguous_ranges(
3937    values: impl Iterator<Item = u32>,
3938    max_len: usize,
3939) -> impl Iterator<Item = Range<u32>> {
3940    let mut values = values;
3941    let mut current_range: Option<Range<u32>> = None;
3942    std::iter::from_fn(move || loop {
3943        if let Some(value) = values.next() {
3944            if let Some(range) = &mut current_range {
3945                if value == range.end && range.len() < max_len {
3946                    range.end += 1;
3947                    continue;
3948                }
3949            }
3950
3951            let prev_range = current_range.clone();
3952            current_range = Some(value..(value + 1));
3953            if prev_range.is_some() {
3954                return prev_range;
3955            }
3956        } else {
3957            return current_range.take();
3958        }
3959    })
3960}
3961
3962/// Returns the [CharKind] for the given character. When a scope is provided,
3963/// the function checks if the character is considered a word character
3964/// based on the language scope's word character settings.
3965pub fn char_kind(scope: &Option<LanguageScope>, c: char) -> CharKind {
3966    if c.is_whitespace() {
3967        return CharKind::Whitespace;
3968    } else if c.is_alphanumeric() || c == '_' {
3969        return CharKind::Word;
3970    }
3971
3972    if let Some(scope) = scope {
3973        if let Some(characters) = scope.word_characters() {
3974            if characters.contains(&c) {
3975                return CharKind::Word;
3976            }
3977        }
3978    }
3979
3980    CharKind::Punctuation
3981}
3982
3983/// Find all of the ranges of whitespace that occur at the ends of lines
3984/// in the given rope.
3985///
3986/// This could also be done with a regex search, but this implementation
3987/// avoids copying text.
3988pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
3989    let mut ranges = Vec::new();
3990
3991    let mut offset = 0;
3992    let mut prev_chunk_trailing_whitespace_range = 0..0;
3993    for chunk in rope.chunks() {
3994        let mut prev_line_trailing_whitespace_range = 0..0;
3995        for (i, line) in chunk.split('\n').enumerate() {
3996            let line_end_offset = offset + line.len();
3997            let trimmed_line_len = line.trim_end_matches(|c| matches!(c, ' ' | '\t')).len();
3998            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
3999
4000            if i == 0 && trimmed_line_len == 0 {
4001                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4002            }
4003            if !prev_line_trailing_whitespace_range.is_empty() {
4004                ranges.push(prev_line_trailing_whitespace_range);
4005            }
4006
4007            offset = line_end_offset + 1;
4008            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4009        }
4010
4011        offset -= 1;
4012        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4013    }
4014
4015    if !prev_chunk_trailing_whitespace_range.is_empty() {
4016        ranges.push(prev_chunk_trailing_whitespace_range);
4017    }
4018
4019    ranges
4020}