buffer.rs

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