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