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