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        self.capability != Capability::ReadOnly
1918            && (self.has_conflict
1919                || self.file.as_ref().map_or(false, |file| {
1920                    matches!(file.disk_state(), DiskState::New | DiskState::Deleted)
1921                })
1922                || self.has_unsaved_edits())
1923    }
1924
1925    /// Checks if the buffer and its file have both changed since the buffer
1926    /// was last saved or reloaded.
1927    pub fn has_conflict(&self) -> bool {
1928        if self.has_conflict {
1929            return true;
1930        }
1931        let Some(file) = self.file.as_ref() else {
1932            return false;
1933        };
1934        match file.disk_state() {
1935            DiskState::New => false,
1936            DiskState::Present { mtime } => match self.saved_mtime {
1937                Some(saved_mtime) => {
1938                    mtime.bad_is_greater_than(saved_mtime) && self.has_unsaved_edits()
1939                }
1940                None => true,
1941            },
1942            DiskState::Deleted => true,
1943        }
1944    }
1945
1946    /// Gets a [`Subscription`] that tracks all of the changes to the buffer's text.
1947    pub fn subscribe(&mut self) -> Subscription {
1948        self.text.subscribe()
1949    }
1950
1951    /// Starts a transaction, if one is not already in-progress. When undoing or
1952    /// redoing edits, all of the edits performed within a transaction are undone
1953    /// or redone together.
1954    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1955        self.start_transaction_at(Instant::now())
1956    }
1957
1958    /// Starts a transaction, providing the current time. Subsequent transactions
1959    /// that occur within a short period of time will be grouped together. This
1960    /// is controlled by the buffer's undo grouping duration.
1961    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1962        self.transaction_depth += 1;
1963        if self.was_dirty_before_starting_transaction.is_none() {
1964            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
1965        }
1966        self.text.start_transaction_at(now)
1967    }
1968
1969    /// Terminates the current transaction, if this is the outermost transaction.
1970    pub fn end_transaction(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
1971        self.end_transaction_at(Instant::now(), cx)
1972    }
1973
1974    /// Terminates the current transaction, providing the current time. Subsequent transactions
1975    /// that occur within a short period of time will be grouped together. This
1976    /// is controlled by the buffer's undo grouping duration.
1977    pub fn end_transaction_at(
1978        &mut self,
1979        now: Instant,
1980        cx: &mut Context<Self>,
1981    ) -> Option<TransactionId> {
1982        assert!(self.transaction_depth > 0);
1983        self.transaction_depth -= 1;
1984        let was_dirty = if self.transaction_depth == 0 {
1985            self.was_dirty_before_starting_transaction.take().unwrap()
1986        } else {
1987            false
1988        };
1989        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1990            self.did_edit(&start_version, was_dirty, cx);
1991            Some(transaction_id)
1992        } else {
1993            None
1994        }
1995    }
1996
1997    /// Manually add a transaction to the buffer's undo history.
1998    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1999        self.text.push_transaction(transaction, now);
2000    }
2001
2002    /// Prevent the last transaction from being grouped with any subsequent transactions,
2003    /// even if they occur with the buffer's undo grouping duration.
2004    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
2005        self.text.finalize_last_transaction()
2006    }
2007
2008    /// Manually group all changes since a given transaction.
2009    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
2010        self.text.group_until_transaction(transaction_id);
2011    }
2012
2013    /// Manually remove a transaction from the buffer's undo history
2014    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
2015        self.text.forget_transaction(transaction_id);
2016    }
2017
2018    /// Manually merge two adjacent transactions in the buffer's undo history.
2019    pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
2020        self.text.merge_transactions(transaction, destination);
2021    }
2022
2023    /// Waits for the buffer to receive operations with the given timestamps.
2024    pub fn wait_for_edits(
2025        &mut self,
2026        edit_ids: impl IntoIterator<Item = clock::Lamport>,
2027    ) -> impl Future<Output = Result<()>> {
2028        self.text.wait_for_edits(edit_ids)
2029    }
2030
2031    /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
2032    pub fn wait_for_anchors(
2033        &mut self,
2034        anchors: impl IntoIterator<Item = Anchor>,
2035    ) -> impl 'static + Future<Output = Result<()>> {
2036        self.text.wait_for_anchors(anchors)
2037    }
2038
2039    /// Waits for the buffer to receive operations up to the given version.
2040    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
2041        self.text.wait_for_version(version)
2042    }
2043
2044    /// Forces all futures returned by [`Buffer::wait_for_version`], [`Buffer::wait_for_edits`], or
2045    /// [`Buffer::wait_for_version`] to resolve with an error.
2046    pub fn give_up_waiting(&mut self) {
2047        self.text.give_up_waiting();
2048    }
2049
2050    /// Stores a set of selections that should be broadcasted to all of the buffer's replicas.
2051    pub fn set_active_selections(
2052        &mut self,
2053        selections: Arc<[Selection<Anchor>]>,
2054        line_mode: bool,
2055        cursor_shape: CursorShape,
2056        cx: &mut Context<Self>,
2057    ) {
2058        let lamport_timestamp = self.text.lamport_clock.tick();
2059        self.remote_selections.insert(
2060            self.text.replica_id(),
2061            SelectionSet {
2062                selections: selections.clone(),
2063                lamport_timestamp,
2064                line_mode,
2065                cursor_shape,
2066            },
2067        );
2068        self.send_operation(
2069            Operation::UpdateSelections {
2070                selections,
2071                line_mode,
2072                lamport_timestamp,
2073                cursor_shape,
2074            },
2075            true,
2076            cx,
2077        );
2078        self.non_text_state_update_count += 1;
2079        cx.notify();
2080    }
2081
2082    /// Clears the selections, so that other replicas of the buffer do not see any selections for
2083    /// this replica.
2084    pub fn remove_active_selections(&mut self, cx: &mut Context<Self>) {
2085        if self
2086            .remote_selections
2087            .get(&self.text.replica_id())
2088            .map_or(true, |set| !set.selections.is_empty())
2089        {
2090            self.set_active_selections(Arc::default(), false, Default::default(), cx);
2091        }
2092    }
2093
2094    /// Replaces the buffer's entire text.
2095    pub fn set_text<T>(&mut self, text: T, cx: &mut Context<Self>) -> Option<clock::Lamport>
2096    where
2097        T: Into<Arc<str>>,
2098    {
2099        self.autoindent_requests.clear();
2100        self.edit([(0..self.len(), text)], None, cx)
2101    }
2102
2103    /// Applies the given edits to the buffer. Each edit is specified as a range of text to
2104    /// delete, and a string of text to insert at that location.
2105    ///
2106    /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
2107    /// request for the edited ranges, which will be processed when the buffer finishes
2108    /// parsing.
2109    ///
2110    /// Parsing takes place at the end of a transaction, and may compute synchronously
2111    /// or asynchronously, depending on the changes.
2112    pub fn edit<I, S, T>(
2113        &mut self,
2114        edits_iter: I,
2115        autoindent_mode: Option<AutoindentMode>,
2116        cx: &mut Context<Self>,
2117    ) -> Option<clock::Lamport>
2118    where
2119        I: IntoIterator<Item = (Range<S>, T)>,
2120        S: ToOffset,
2121        T: Into<Arc<str>>,
2122    {
2123        // Skip invalid edits and coalesce contiguous ones.
2124        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
2125        for (range, new_text) in edits_iter {
2126            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2127            if range.start > range.end {
2128                mem::swap(&mut range.start, &mut range.end);
2129            }
2130            let new_text = new_text.into();
2131            if !new_text.is_empty() || !range.is_empty() {
2132                if let Some((prev_range, prev_text)) = edits.last_mut() {
2133                    if prev_range.end >= range.start {
2134                        prev_range.end = cmp::max(prev_range.end, range.end);
2135                        *prev_text = format!("{prev_text}{new_text}").into();
2136                    } else {
2137                        edits.push((range, new_text));
2138                    }
2139                } else {
2140                    edits.push((range, new_text));
2141                }
2142            }
2143        }
2144        if edits.is_empty() {
2145            return None;
2146        }
2147
2148        self.start_transaction();
2149        self.pending_autoindent.take();
2150        let autoindent_request = autoindent_mode
2151            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
2152
2153        let edit_operation = self.text.edit(edits.iter().cloned());
2154        let edit_id = edit_operation.timestamp();
2155
2156        if let Some((before_edit, mode)) = autoindent_request {
2157            let mut delta = 0isize;
2158            let entries = edits
2159                .into_iter()
2160                .enumerate()
2161                .zip(&edit_operation.as_edit().unwrap().new_text)
2162                .map(|((ix, (range, _)), new_text)| {
2163                    let new_text_length = new_text.len();
2164                    let old_start = range.start.to_point(&before_edit);
2165                    let new_start = (delta + range.start as isize) as usize;
2166                    let range_len = range.end - range.start;
2167                    delta += new_text_length as isize - range_len as isize;
2168
2169                    // Decide what range of the insertion to auto-indent, and whether
2170                    // the first line of the insertion should be considered a newly-inserted line
2171                    // or an edit to an existing line.
2172                    let mut range_of_insertion_to_indent = 0..new_text_length;
2173                    let mut first_line_is_new = true;
2174
2175                    let old_line_start = before_edit.indent_size_for_line(old_start.row).len;
2176                    let old_line_end = before_edit.line_len(old_start.row);
2177
2178                    if old_start.column > old_line_start {
2179                        first_line_is_new = false;
2180                    }
2181
2182                    if !new_text.contains('\n')
2183                        && (old_start.column + (range_len as u32) < old_line_end
2184                            || old_line_end == old_line_start)
2185                    {
2186                        first_line_is_new = false;
2187                    }
2188
2189                    // When inserting text starting with a newline, avoid auto-indenting the
2190                    // previous line.
2191                    if new_text.starts_with('\n') {
2192                        range_of_insertion_to_indent.start += 1;
2193                        first_line_is_new = true;
2194                    }
2195
2196                    let mut original_indent_column = None;
2197                    if let AutoindentMode::Block {
2198                        original_indent_columns,
2199                    } = &mode
2200                    {
2201                        original_indent_column =
2202                            Some(original_indent_columns.get(ix).copied().unwrap_or_else(|| {
2203                                indent_size_for_text(
2204                                    new_text[range_of_insertion_to_indent.clone()].chars(),
2205                                )
2206                                .len
2207                            }));
2208
2209                        // Avoid auto-indenting the line after the edit.
2210                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
2211                            range_of_insertion_to_indent.end -= 1;
2212                        }
2213                    }
2214
2215                    AutoindentRequestEntry {
2216                        first_line_is_new,
2217                        original_indent_column,
2218                        indent_size: before_edit.language_indent_size_at(range.start, cx),
2219                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
2220                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
2221                    }
2222                })
2223                .collect();
2224
2225            self.autoindent_requests.push(Arc::new(AutoindentRequest {
2226                before_edit,
2227                entries,
2228                is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
2229                ignore_empty_lines: false,
2230            }));
2231        }
2232
2233        self.end_transaction(cx);
2234        self.send_operation(Operation::Buffer(edit_operation), true, cx);
2235        Some(edit_id)
2236    }
2237
2238    fn did_edit(&mut self, old_version: &clock::Global, was_dirty: bool, cx: &mut Context<Self>) {
2239        if self.edits_since::<usize>(old_version).next().is_none() {
2240            return;
2241        }
2242
2243        self.reparse(cx);
2244
2245        cx.emit(BufferEvent::Edited);
2246        if was_dirty != self.is_dirty() {
2247            cx.emit(BufferEvent::DirtyChanged);
2248        }
2249        cx.notify();
2250    }
2251
2252    pub fn autoindent_ranges<I, T>(&mut self, ranges: I, cx: &mut Context<Self>)
2253    where
2254        I: IntoIterator<Item = Range<T>>,
2255        T: ToOffset + Copy,
2256    {
2257        let before_edit = self.snapshot();
2258        let entries = ranges
2259            .into_iter()
2260            .map(|range| AutoindentRequestEntry {
2261                range: before_edit.anchor_before(range.start)..before_edit.anchor_after(range.end),
2262                first_line_is_new: true,
2263                indent_size: before_edit.language_indent_size_at(range.start, cx),
2264                original_indent_column: None,
2265            })
2266            .collect();
2267        self.autoindent_requests.push(Arc::new(AutoindentRequest {
2268            before_edit,
2269            entries,
2270            is_block_mode: false,
2271            ignore_empty_lines: true,
2272        }));
2273        self.request_autoindent(cx);
2274    }
2275
2276    // Inserts newlines at the given position to create an empty line, returning the start of the new line.
2277    // You can also request the insertion of empty lines above and below the line starting at the returned point.
2278    pub fn insert_empty_line(
2279        &mut self,
2280        position: impl ToPoint,
2281        space_above: bool,
2282        space_below: bool,
2283        cx: &mut Context<Self>,
2284    ) -> Point {
2285        let mut position = position.to_point(self);
2286
2287        self.start_transaction();
2288
2289        self.edit(
2290            [(position..position, "\n")],
2291            Some(AutoindentMode::EachLine),
2292            cx,
2293        );
2294
2295        if position.column > 0 {
2296            position += Point::new(1, 0);
2297        }
2298
2299        if !self.is_line_blank(position.row) {
2300            self.edit(
2301                [(position..position, "\n")],
2302                Some(AutoindentMode::EachLine),
2303                cx,
2304            );
2305        }
2306
2307        if space_above && position.row > 0 && !self.is_line_blank(position.row - 1) {
2308            self.edit(
2309                [(position..position, "\n")],
2310                Some(AutoindentMode::EachLine),
2311                cx,
2312            );
2313            position.row += 1;
2314        }
2315
2316        if space_below
2317            && (position.row == self.max_point().row || !self.is_line_blank(position.row + 1))
2318        {
2319            self.edit(
2320                [(position..position, "\n")],
2321                Some(AutoindentMode::EachLine),
2322                cx,
2323            );
2324        }
2325
2326        self.end_transaction(cx);
2327
2328        position
2329    }
2330
2331    /// Applies the given remote operations to the buffer.
2332    pub fn apply_ops<I: IntoIterator<Item = Operation>>(&mut self, ops: I, cx: &mut Context<Self>) {
2333        self.pending_autoindent.take();
2334        let was_dirty = self.is_dirty();
2335        let old_version = self.version.clone();
2336        let mut deferred_ops = Vec::new();
2337        let buffer_ops = ops
2338            .into_iter()
2339            .filter_map(|op| match op {
2340                Operation::Buffer(op) => Some(op),
2341                _ => {
2342                    if self.can_apply_op(&op) {
2343                        self.apply_op(op, cx);
2344                    } else {
2345                        deferred_ops.push(op);
2346                    }
2347                    None
2348                }
2349            })
2350            .collect::<Vec<_>>();
2351        for operation in buffer_ops.iter() {
2352            self.send_operation(Operation::Buffer(operation.clone()), false, cx);
2353        }
2354        self.text.apply_ops(buffer_ops);
2355        self.deferred_ops.insert(deferred_ops);
2356        self.flush_deferred_ops(cx);
2357        self.did_edit(&old_version, was_dirty, cx);
2358        // Notify independently of whether the buffer was edited as the operations could include a
2359        // selection update.
2360        cx.notify();
2361    }
2362
2363    fn flush_deferred_ops(&mut self, cx: &mut Context<Self>) {
2364        let mut deferred_ops = Vec::new();
2365        for op in self.deferred_ops.drain().iter().cloned() {
2366            if self.can_apply_op(&op) {
2367                self.apply_op(op, cx);
2368            } else {
2369                deferred_ops.push(op);
2370            }
2371        }
2372        self.deferred_ops.insert(deferred_ops);
2373    }
2374
2375    pub fn has_deferred_ops(&self) -> bool {
2376        !self.deferred_ops.is_empty() || self.text.has_deferred_ops()
2377    }
2378
2379    fn can_apply_op(&self, operation: &Operation) -> bool {
2380        match operation {
2381            Operation::Buffer(_) => {
2382                unreachable!("buffer operations should never be applied at this layer")
2383            }
2384            Operation::UpdateDiagnostics {
2385                diagnostics: diagnostic_set,
2386                ..
2387            } => diagnostic_set.iter().all(|diagnostic| {
2388                self.text.can_resolve(&diagnostic.range.start)
2389                    && self.text.can_resolve(&diagnostic.range.end)
2390            }),
2391            Operation::UpdateSelections { selections, .. } => selections
2392                .iter()
2393                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
2394            Operation::UpdateCompletionTriggers { .. } => true,
2395        }
2396    }
2397
2398    fn apply_op(&mut self, operation: Operation, cx: &mut Context<Self>) {
2399        match operation {
2400            Operation::Buffer(_) => {
2401                unreachable!("buffer operations should never be applied at this layer")
2402            }
2403            Operation::UpdateDiagnostics {
2404                server_id,
2405                diagnostics: diagnostic_set,
2406                lamport_timestamp,
2407            } => {
2408                let snapshot = self.snapshot();
2409                self.apply_diagnostic_update(
2410                    server_id,
2411                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
2412                    lamport_timestamp,
2413                    cx,
2414                );
2415            }
2416            Operation::UpdateSelections {
2417                selections,
2418                lamport_timestamp,
2419                line_mode,
2420                cursor_shape,
2421            } => {
2422                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
2423                    if set.lamport_timestamp > lamport_timestamp {
2424                        return;
2425                    }
2426                }
2427
2428                self.remote_selections.insert(
2429                    lamport_timestamp.replica_id,
2430                    SelectionSet {
2431                        selections,
2432                        lamport_timestamp,
2433                        line_mode,
2434                        cursor_shape,
2435                    },
2436                );
2437                self.text.lamport_clock.observe(lamport_timestamp);
2438                self.non_text_state_update_count += 1;
2439            }
2440            Operation::UpdateCompletionTriggers {
2441                triggers,
2442                lamport_timestamp,
2443                server_id,
2444            } => {
2445                if triggers.is_empty() {
2446                    self.completion_triggers_per_language_server
2447                        .remove(&server_id);
2448                    self.completion_triggers = self
2449                        .completion_triggers_per_language_server
2450                        .values()
2451                        .flat_map(|triggers| triggers.into_iter().cloned())
2452                        .collect();
2453                } else {
2454                    self.completion_triggers_per_language_server
2455                        .insert(server_id, triggers.iter().cloned().collect());
2456                    self.completion_triggers.extend(triggers);
2457                }
2458                self.text.lamport_clock.observe(lamport_timestamp);
2459            }
2460        }
2461    }
2462
2463    fn apply_diagnostic_update(
2464        &mut self,
2465        server_id: LanguageServerId,
2466        diagnostics: DiagnosticSet,
2467        lamport_timestamp: clock::Lamport,
2468        cx: &mut Context<Self>,
2469    ) {
2470        if lamport_timestamp > self.diagnostics_timestamp {
2471            let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
2472            if diagnostics.is_empty() {
2473                if let Ok(ix) = ix {
2474                    self.diagnostics.remove(ix);
2475                }
2476            } else {
2477                match ix {
2478                    Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
2479                    Ok(ix) => self.diagnostics[ix].1 = diagnostics,
2480                };
2481            }
2482            self.diagnostics_timestamp = lamport_timestamp;
2483            self.non_text_state_update_count += 1;
2484            self.text.lamport_clock.observe(lamport_timestamp);
2485            cx.notify();
2486            cx.emit(BufferEvent::DiagnosticsUpdated);
2487        }
2488    }
2489
2490    fn send_operation(&self, operation: Operation, is_local: bool, cx: &mut Context<Self>) {
2491        cx.emit(BufferEvent::Operation {
2492            operation,
2493            is_local,
2494        });
2495    }
2496
2497    /// Removes the selections for a given peer.
2498    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut Context<Self>) {
2499        self.remote_selections.remove(&replica_id);
2500        cx.notify();
2501    }
2502
2503    /// Undoes the most recent transaction.
2504    pub fn undo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2505        let was_dirty = self.is_dirty();
2506        let old_version = self.version.clone();
2507
2508        if let Some((transaction_id, operation)) = self.text.undo() {
2509            self.send_operation(Operation::Buffer(operation), true, cx);
2510            self.did_edit(&old_version, was_dirty, cx);
2511            Some(transaction_id)
2512        } else {
2513            None
2514        }
2515    }
2516
2517    /// Manually undoes a specific transaction in the buffer's undo history.
2518    pub fn undo_transaction(
2519        &mut self,
2520        transaction_id: TransactionId,
2521        cx: &mut Context<Self>,
2522    ) -> bool {
2523        let was_dirty = self.is_dirty();
2524        let old_version = self.version.clone();
2525        if let Some(operation) = self.text.undo_transaction(transaction_id) {
2526            self.send_operation(Operation::Buffer(operation), true, cx);
2527            self.did_edit(&old_version, was_dirty, cx);
2528            true
2529        } else {
2530            false
2531        }
2532    }
2533
2534    /// Manually undoes all changes after a given transaction in the buffer's undo history.
2535    pub fn undo_to_transaction(
2536        &mut self,
2537        transaction_id: TransactionId,
2538        cx: &mut Context<Self>,
2539    ) -> bool {
2540        let was_dirty = self.is_dirty();
2541        let old_version = self.version.clone();
2542
2543        let operations = self.text.undo_to_transaction(transaction_id);
2544        let undone = !operations.is_empty();
2545        for operation in operations {
2546            self.send_operation(Operation::Buffer(operation), true, cx);
2547        }
2548        if undone {
2549            self.did_edit(&old_version, was_dirty, cx)
2550        }
2551        undone
2552    }
2553
2554    pub fn undo_operations(&mut self, counts: HashMap<Lamport, u32>, cx: &mut Context<Buffer>) {
2555        let was_dirty = self.is_dirty();
2556        let operation = self.text.undo_operations(counts);
2557        let old_version = self.version.clone();
2558        self.send_operation(Operation::Buffer(operation), true, cx);
2559        self.did_edit(&old_version, was_dirty, cx);
2560    }
2561
2562    /// Manually redoes a specific transaction in the buffer's redo history.
2563    pub fn redo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2564        let was_dirty = self.is_dirty();
2565        let old_version = self.version.clone();
2566
2567        if let Some((transaction_id, operation)) = self.text.redo() {
2568            self.send_operation(Operation::Buffer(operation), true, cx);
2569            self.did_edit(&old_version, was_dirty, cx);
2570            Some(transaction_id)
2571        } else {
2572            None
2573        }
2574    }
2575
2576    /// Manually undoes all changes until a given transaction in the buffer's redo history.
2577    pub fn redo_to_transaction(
2578        &mut self,
2579        transaction_id: TransactionId,
2580        cx: &mut Context<Self>,
2581    ) -> bool {
2582        let was_dirty = self.is_dirty();
2583        let old_version = self.version.clone();
2584
2585        let operations = self.text.redo_to_transaction(transaction_id);
2586        let redone = !operations.is_empty();
2587        for operation in operations {
2588            self.send_operation(Operation::Buffer(operation), true, cx);
2589        }
2590        if redone {
2591            self.did_edit(&old_version, was_dirty, cx)
2592        }
2593        redone
2594    }
2595
2596    /// Override current completion triggers with the user-provided completion triggers.
2597    pub fn set_completion_triggers(
2598        &mut self,
2599        server_id: LanguageServerId,
2600        triggers: BTreeSet<String>,
2601        cx: &mut Context<Self>,
2602    ) {
2603        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2604        if triggers.is_empty() {
2605            self.completion_triggers_per_language_server
2606                .remove(&server_id);
2607            self.completion_triggers = self
2608                .completion_triggers_per_language_server
2609                .values()
2610                .flat_map(|triggers| triggers.into_iter().cloned())
2611                .collect();
2612        } else {
2613            self.completion_triggers_per_language_server
2614                .insert(server_id, triggers.clone());
2615            self.completion_triggers.extend(triggers.iter().cloned());
2616        }
2617        self.send_operation(
2618            Operation::UpdateCompletionTriggers {
2619                triggers: triggers.iter().cloned().collect(),
2620                lamport_timestamp: self.completion_triggers_timestamp,
2621                server_id,
2622            },
2623            true,
2624            cx,
2625        );
2626        cx.notify();
2627    }
2628
2629    /// Returns a list of strings which trigger a completion menu for this language.
2630    /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2631    pub fn completion_triggers(&self) -> &BTreeSet<String> {
2632        &self.completion_triggers
2633    }
2634
2635    /// Call this directly after performing edits to prevent the preview tab
2636    /// from being dismissed by those edits. It causes `should_dismiss_preview`
2637    /// to return false until there are additional edits.
2638    pub fn refresh_preview(&mut self) {
2639        self.preview_version = self.version.clone();
2640    }
2641
2642    /// Whether we should preserve the preview status of a tab containing this buffer.
2643    pub fn preserve_preview(&self) -> bool {
2644        !self.has_edits_since(&self.preview_version)
2645    }
2646}
2647
2648#[doc(hidden)]
2649#[cfg(any(test, feature = "test-support"))]
2650impl Buffer {
2651    pub fn edit_via_marked_text(
2652        &mut self,
2653        marked_string: &str,
2654        autoindent_mode: Option<AutoindentMode>,
2655        cx: &mut Context<Self>,
2656    ) {
2657        let edits = self.edits_for_marked_text(marked_string);
2658        self.edit(edits, autoindent_mode, cx);
2659    }
2660
2661    pub fn set_group_interval(&mut self, group_interval: Duration) {
2662        self.text.set_group_interval(group_interval);
2663    }
2664
2665    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize, cx: &mut Context<Self>)
2666    where
2667        T: rand::Rng,
2668    {
2669        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2670        let mut last_end = None;
2671        for _ in 0..old_range_count {
2672            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2673                break;
2674            }
2675
2676            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2677            let mut range = self.random_byte_range(new_start, rng);
2678            if rng.gen_bool(0.2) {
2679                mem::swap(&mut range.start, &mut range.end);
2680            }
2681            last_end = Some(range.end);
2682
2683            let new_text_len = rng.gen_range(0..10);
2684            let mut new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2685            new_text = new_text.to_uppercase();
2686
2687            edits.push((range, new_text));
2688        }
2689        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2690        self.edit(edits, None, cx);
2691    }
2692
2693    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut Context<Self>) {
2694        let was_dirty = self.is_dirty();
2695        let old_version = self.version.clone();
2696
2697        let ops = self.text.randomly_undo_redo(rng);
2698        if !ops.is_empty() {
2699            for op in ops {
2700                self.send_operation(Operation::Buffer(op), true, cx);
2701                self.did_edit(&old_version, was_dirty, cx);
2702            }
2703        }
2704    }
2705}
2706
2707impl EventEmitter<BufferEvent> for Buffer {}
2708
2709impl Deref for Buffer {
2710    type Target = TextBuffer;
2711
2712    fn deref(&self) -> &Self::Target {
2713        &self.text
2714    }
2715}
2716
2717impl BufferSnapshot {
2718    /// Returns [`IndentSize`] for a given line that respects user settings and /// language preferences.
2719    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2720        indent_size_for_line(self, row)
2721    }
2722    /// Returns [`IndentSize`] for a given position that respects user settings
2723    /// and language preferences.
2724    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &App) -> IndentSize {
2725        let settings = language_settings(
2726            self.language_at(position).map(|l| l.name()),
2727            self.file(),
2728            cx,
2729        );
2730        if settings.hard_tabs {
2731            IndentSize::tab()
2732        } else {
2733            IndentSize::spaces(settings.tab_size.get())
2734        }
2735    }
2736
2737    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2738    /// is passed in as `single_indent_size`.
2739    pub fn suggested_indents(
2740        &self,
2741        rows: impl Iterator<Item = u32>,
2742        single_indent_size: IndentSize,
2743    ) -> BTreeMap<u32, IndentSize> {
2744        let mut result = BTreeMap::new();
2745
2746        for row_range in contiguous_ranges(rows, 10) {
2747            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2748                Some(suggestions) => suggestions,
2749                _ => break,
2750            };
2751
2752            for (row, suggestion) in row_range.zip(suggestions) {
2753                let indent_size = if let Some(suggestion) = suggestion {
2754                    result
2755                        .get(&suggestion.basis_row)
2756                        .copied()
2757                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2758                        .with_delta(suggestion.delta, single_indent_size)
2759                } else {
2760                    self.indent_size_for_line(row)
2761                };
2762
2763                result.insert(row, indent_size);
2764            }
2765        }
2766
2767        result
2768    }
2769
2770    fn suggest_autoindents(
2771        &self,
2772        row_range: Range<u32>,
2773    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2774        let config = &self.language.as_ref()?.config;
2775        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2776
2777        // Find the suggested indentation ranges based on the syntax tree.
2778        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2779        let end = Point::new(row_range.end, 0);
2780        let range = (start..end).to_offset(&self.text);
2781        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2782            Some(&grammar.indents_config.as_ref()?.query)
2783        });
2784        let indent_configs = matches
2785            .grammars()
2786            .iter()
2787            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2788            .collect::<Vec<_>>();
2789
2790        let mut indent_ranges = Vec::<Range<Point>>::new();
2791        let mut outdent_positions = Vec::<Point>::new();
2792        while let Some(mat) = matches.peek() {
2793            let mut start: Option<Point> = None;
2794            let mut end: Option<Point> = None;
2795
2796            let config = &indent_configs[mat.grammar_index];
2797            for capture in mat.captures {
2798                if capture.index == config.indent_capture_ix {
2799                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2800                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2801                } else if Some(capture.index) == config.start_capture_ix {
2802                    start = Some(Point::from_ts_point(capture.node.end_position()));
2803                } else if Some(capture.index) == config.end_capture_ix {
2804                    end = Some(Point::from_ts_point(capture.node.start_position()));
2805                } else if Some(capture.index) == config.outdent_capture_ix {
2806                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2807                }
2808            }
2809
2810            matches.advance();
2811            if let Some((start, end)) = start.zip(end) {
2812                if start.row == end.row {
2813                    continue;
2814                }
2815
2816                let range = start..end;
2817                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2818                    Err(ix) => indent_ranges.insert(ix, range),
2819                    Ok(ix) => {
2820                        let prev_range = &mut indent_ranges[ix];
2821                        prev_range.end = prev_range.end.max(range.end);
2822                    }
2823                }
2824            }
2825        }
2826
2827        let mut error_ranges = Vec::<Range<Point>>::new();
2828        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2829            Some(&grammar.error_query)
2830        });
2831        while let Some(mat) = matches.peek() {
2832            let node = mat.captures[0].node;
2833            let start = Point::from_ts_point(node.start_position());
2834            let end = Point::from_ts_point(node.end_position());
2835            let range = start..end;
2836            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2837                Ok(ix) | Err(ix) => ix,
2838            };
2839            let mut end_ix = ix;
2840            while let Some(existing_range) = error_ranges.get(end_ix) {
2841                if existing_range.end < end {
2842                    end_ix += 1;
2843                } else {
2844                    break;
2845                }
2846            }
2847            error_ranges.splice(ix..end_ix, [range]);
2848            matches.advance();
2849        }
2850
2851        outdent_positions.sort();
2852        for outdent_position in outdent_positions {
2853            // find the innermost indent range containing this outdent_position
2854            // set its end to the outdent position
2855            if let Some(range_to_truncate) = indent_ranges
2856                .iter_mut()
2857                .filter(|indent_range| indent_range.contains(&outdent_position))
2858                .last()
2859            {
2860                range_to_truncate.end = outdent_position;
2861            }
2862        }
2863
2864        // Find the suggested indentation increases and decreased based on regexes.
2865        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2866        self.for_each_line(
2867            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2868                ..Point::new(row_range.end, 0),
2869            |row, line| {
2870                if config
2871                    .decrease_indent_pattern
2872                    .as_ref()
2873                    .map_or(false, |regex| regex.is_match(line))
2874                {
2875                    indent_change_rows.push((row, Ordering::Less));
2876                }
2877                if config
2878                    .increase_indent_pattern
2879                    .as_ref()
2880                    .map_or(false, |regex| regex.is_match(line))
2881                {
2882                    indent_change_rows.push((row + 1, Ordering::Greater));
2883                }
2884            },
2885        );
2886
2887        let mut indent_changes = indent_change_rows.into_iter().peekable();
2888        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2889            prev_non_blank_row.unwrap_or(0)
2890        } else {
2891            row_range.start.saturating_sub(1)
2892        };
2893        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2894        Some(row_range.map(move |row| {
2895            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2896
2897            let mut indent_from_prev_row = false;
2898            let mut outdent_from_prev_row = false;
2899            let mut outdent_to_row = u32::MAX;
2900            let mut from_regex = false;
2901
2902            while let Some((indent_row, delta)) = indent_changes.peek() {
2903                match indent_row.cmp(&row) {
2904                    Ordering::Equal => match delta {
2905                        Ordering::Less => {
2906                            from_regex = true;
2907                            outdent_from_prev_row = true
2908                        }
2909                        Ordering::Greater => {
2910                            indent_from_prev_row = true;
2911                            from_regex = true
2912                        }
2913                        _ => {}
2914                    },
2915
2916                    Ordering::Greater => break,
2917                    Ordering::Less => {}
2918                }
2919
2920                indent_changes.next();
2921            }
2922
2923            for range in &indent_ranges {
2924                if range.start.row >= row {
2925                    break;
2926                }
2927                if range.start.row == prev_row && range.end > row_start {
2928                    indent_from_prev_row = true;
2929                }
2930                if range.end > prev_row_start && range.end <= row_start {
2931                    outdent_to_row = outdent_to_row.min(range.start.row);
2932                }
2933            }
2934
2935            let within_error = error_ranges
2936                .iter()
2937                .any(|e| e.start.row < row && e.end > row_start);
2938
2939            let suggestion = if outdent_to_row == prev_row
2940                || (outdent_from_prev_row && indent_from_prev_row)
2941            {
2942                Some(IndentSuggestion {
2943                    basis_row: prev_row,
2944                    delta: Ordering::Equal,
2945                    within_error: within_error && !from_regex,
2946                })
2947            } else if indent_from_prev_row {
2948                Some(IndentSuggestion {
2949                    basis_row: prev_row,
2950                    delta: Ordering::Greater,
2951                    within_error: within_error && !from_regex,
2952                })
2953            } else if outdent_to_row < prev_row {
2954                Some(IndentSuggestion {
2955                    basis_row: outdent_to_row,
2956                    delta: Ordering::Equal,
2957                    within_error: within_error && !from_regex,
2958                })
2959            } else if outdent_from_prev_row {
2960                Some(IndentSuggestion {
2961                    basis_row: prev_row,
2962                    delta: Ordering::Less,
2963                    within_error: within_error && !from_regex,
2964                })
2965            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
2966            {
2967                Some(IndentSuggestion {
2968                    basis_row: prev_row,
2969                    delta: Ordering::Equal,
2970                    within_error: within_error && !from_regex,
2971                })
2972            } else {
2973                None
2974            };
2975
2976            prev_row = row;
2977            prev_row_start = row_start;
2978            suggestion
2979        }))
2980    }
2981
2982    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2983        while row > 0 {
2984            row -= 1;
2985            if !self.is_line_blank(row) {
2986                return Some(row);
2987            }
2988        }
2989        None
2990    }
2991
2992    fn get_highlights(&self, range: Range<usize>) -> (SyntaxMapCaptures, Vec<HighlightMap>) {
2993        let captures = self.syntax.captures(range, &self.text, |grammar| {
2994            grammar.highlights_query.as_ref()
2995        });
2996        let highlight_maps = captures
2997            .grammars()
2998            .iter()
2999            .map(|grammar| grammar.highlight_map())
3000            .collect();
3001        (captures, highlight_maps)
3002    }
3003
3004    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
3005    /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
3006    /// returned in chunks where each chunk has a single syntax highlighting style and
3007    /// diagnostic status.
3008    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
3009        let range = range.start.to_offset(self)..range.end.to_offset(self);
3010
3011        let mut syntax = None;
3012        if language_aware {
3013            syntax = Some(self.get_highlights(range.clone()));
3014        }
3015        // We want to look at diagnostic spans only when iterating over language-annotated chunks.
3016        let diagnostics = language_aware;
3017        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostics, Some(self))
3018    }
3019
3020    pub fn highlighted_text_for_range<T: ToOffset>(
3021        &self,
3022        range: Range<T>,
3023        override_style: Option<HighlightStyle>,
3024        syntax_theme: &SyntaxTheme,
3025    ) -> HighlightedText {
3026        HighlightedText::from_buffer_range(
3027            range,
3028            &self.text,
3029            &self.syntax,
3030            override_style,
3031            syntax_theme,
3032        )
3033    }
3034
3035    /// Invokes the given callback for each line of text in the given range of the buffer.
3036    /// Uses callback to avoid allocating a string for each line.
3037    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
3038        let mut line = String::new();
3039        let mut row = range.start.row;
3040        for chunk in self
3041            .as_rope()
3042            .chunks_in_range(range.to_offset(self))
3043            .chain(["\n"])
3044        {
3045            for (newline_ix, text) in chunk.split('\n').enumerate() {
3046                if newline_ix > 0 {
3047                    callback(row, &line);
3048                    row += 1;
3049                    line.clear();
3050                }
3051                line.push_str(text);
3052            }
3053        }
3054    }
3055
3056    /// Iterates over every [`SyntaxLayer`] in the buffer.
3057    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
3058        self.syntax
3059            .layers_for_range(0..self.len(), &self.text, true)
3060    }
3061
3062    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
3063        let offset = position.to_offset(self);
3064        self.syntax
3065            .layers_for_range(offset..offset, &self.text, false)
3066            .filter(|l| l.node().end_byte() > offset)
3067            .last()
3068    }
3069
3070    /// Returns the main [`Language`].
3071    pub fn language(&self) -> Option<&Arc<Language>> {
3072        self.language.as_ref()
3073    }
3074
3075    /// Returns the [`Language`] at the given location.
3076    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
3077        self.syntax_layer_at(position)
3078            .map(|info| info.language)
3079            .or(self.language.as_ref())
3080    }
3081
3082    /// Returns the settings for the language at the given location.
3083    pub fn settings_at<'a, D: ToOffset>(
3084        &'a self,
3085        position: D,
3086        cx: &'a App,
3087    ) -> Cow<'a, LanguageSettings> {
3088        language_settings(
3089            self.language_at(position).map(|l| l.name()),
3090            self.file.as_ref(),
3091            cx,
3092        )
3093    }
3094
3095    pub fn char_classifier_at<T: ToOffset>(&self, point: T) -> CharClassifier {
3096        CharClassifier::new(self.language_scope_at(point))
3097    }
3098
3099    /// Returns the [`LanguageScope`] at the given location.
3100    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
3101        let offset = position.to_offset(self);
3102        let mut scope = None;
3103        let mut smallest_range: Option<Range<usize>> = None;
3104
3105        // Use the layer that has the smallest node intersecting the given point.
3106        for layer in self
3107            .syntax
3108            .layers_for_range(offset..offset, &self.text, false)
3109        {
3110            let mut cursor = layer.node().walk();
3111
3112            let mut range = None;
3113            loop {
3114                let child_range = cursor.node().byte_range();
3115                if !child_range.to_inclusive().contains(&offset) {
3116                    break;
3117                }
3118
3119                range = Some(child_range);
3120                if cursor.goto_first_child_for_byte(offset).is_none() {
3121                    break;
3122                }
3123            }
3124
3125            if let Some(range) = range {
3126                if smallest_range
3127                    .as_ref()
3128                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
3129                {
3130                    smallest_range = Some(range);
3131                    scope = Some(LanguageScope {
3132                        language: layer.language.clone(),
3133                        override_id: layer.override_id(offset, &self.text),
3134                    });
3135                }
3136            }
3137        }
3138
3139        scope.or_else(|| {
3140            self.language.clone().map(|language| LanguageScope {
3141                language,
3142                override_id: None,
3143            })
3144        })
3145    }
3146
3147    /// Returns a tuple of the range and character kind of the word
3148    /// surrounding the given position.
3149    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
3150        let mut start = start.to_offset(self);
3151        let mut end = start;
3152        let mut next_chars = self.chars_at(start).peekable();
3153        let mut prev_chars = self.reversed_chars_at(start).peekable();
3154
3155        let classifier = self.char_classifier_at(start);
3156        let word_kind = cmp::max(
3157            prev_chars.peek().copied().map(|c| classifier.kind(c)),
3158            next_chars.peek().copied().map(|c| classifier.kind(c)),
3159        );
3160
3161        for ch in prev_chars {
3162            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3163                start -= ch.len_utf8();
3164            } else {
3165                break;
3166            }
3167        }
3168
3169        for ch in next_chars {
3170            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3171                end += ch.len_utf8();
3172            } else {
3173                break;
3174            }
3175        }
3176
3177        (start..end, word_kind)
3178    }
3179
3180    /// Returns the closest syntax node enclosing the given range.
3181    pub fn syntax_ancestor<'a, T: ToOffset>(
3182        &'a self,
3183        range: Range<T>,
3184    ) -> Option<tree_sitter::Node<'a>> {
3185        let range = range.start.to_offset(self)..range.end.to_offset(self);
3186        let mut result: Option<tree_sitter::Node<'a>> = None;
3187        'outer: for layer in self
3188            .syntax
3189            .layers_for_range(range.clone(), &self.text, true)
3190        {
3191            let mut cursor = layer.node().walk();
3192
3193            // Descend to the first leaf that touches the start of the range,
3194            // and if the range is non-empty, extends beyond the start.
3195            while cursor.goto_first_child_for_byte(range.start).is_some() {
3196                if !range.is_empty() && cursor.node().end_byte() == range.start {
3197                    cursor.goto_next_sibling();
3198                }
3199            }
3200
3201            // Ascend to the smallest ancestor that strictly contains the range.
3202            loop {
3203                let node_range = cursor.node().byte_range();
3204                if node_range.start <= range.start
3205                    && node_range.end >= range.end
3206                    && node_range.len() > range.len()
3207                {
3208                    break;
3209                }
3210                if !cursor.goto_parent() {
3211                    continue 'outer;
3212                }
3213            }
3214
3215            let left_node = cursor.node();
3216            let mut layer_result = left_node;
3217
3218            // For an empty range, try to find another node immediately to the right of the range.
3219            if left_node.end_byte() == range.start {
3220                let mut right_node = None;
3221                while !cursor.goto_next_sibling() {
3222                    if !cursor.goto_parent() {
3223                        break;
3224                    }
3225                }
3226
3227                while cursor.node().start_byte() == range.start {
3228                    right_node = Some(cursor.node());
3229                    if !cursor.goto_first_child() {
3230                        break;
3231                    }
3232                }
3233
3234                // If there is a candidate node on both sides of the (empty) range, then
3235                // decide between the two by favoring a named node over an anonymous token.
3236                // If both nodes are the same in that regard, favor the right one.
3237                if let Some(right_node) = right_node {
3238                    if right_node.is_named() || !left_node.is_named() {
3239                        layer_result = right_node;
3240                    }
3241                }
3242            }
3243
3244            if let Some(previous_result) = &result {
3245                if previous_result.byte_range().len() < layer_result.byte_range().len() {
3246                    continue;
3247                }
3248            }
3249            result = Some(layer_result);
3250        }
3251
3252        result
3253    }
3254
3255    /// Returns the outline for the buffer.
3256    ///
3257    /// This method allows passing an optional [`SyntaxTheme`] to
3258    /// syntax-highlight the returned symbols.
3259    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3260        self.outline_items_containing(0..self.len(), true, theme)
3261            .map(Outline::new)
3262    }
3263
3264    /// Returns all the symbols that contain the given position.
3265    ///
3266    /// This method allows passing an optional [`SyntaxTheme`] to
3267    /// syntax-highlight the returned symbols.
3268    pub fn symbols_containing<T: ToOffset>(
3269        &self,
3270        position: T,
3271        theme: Option<&SyntaxTheme>,
3272    ) -> Option<Vec<OutlineItem<Anchor>>> {
3273        let position = position.to_offset(self);
3274        let mut items = self.outline_items_containing(
3275            position.saturating_sub(1)..self.len().min(position + 1),
3276            false,
3277            theme,
3278        )?;
3279        let mut prev_depth = None;
3280        items.retain(|item| {
3281            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
3282            prev_depth = Some(item.depth);
3283            result
3284        });
3285        Some(items)
3286    }
3287
3288    pub fn outline_range_containing<T: ToOffset>(&self, range: Range<T>) -> Option<Range<Point>> {
3289        let range = range.to_offset(self);
3290        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3291            grammar.outline_config.as_ref().map(|c| &c.query)
3292        });
3293        let configs = matches
3294            .grammars()
3295            .iter()
3296            .map(|g| g.outline_config.as_ref().unwrap())
3297            .collect::<Vec<_>>();
3298
3299        while let Some(mat) = matches.peek() {
3300            let config = &configs[mat.grammar_index];
3301            let containing_item_node = maybe!({
3302                let item_node = mat.captures.iter().find_map(|cap| {
3303                    if cap.index == config.item_capture_ix {
3304                        Some(cap.node)
3305                    } else {
3306                        None
3307                    }
3308                })?;
3309
3310                let item_byte_range = item_node.byte_range();
3311                if item_byte_range.end < range.start || item_byte_range.start > range.end {
3312                    None
3313                } else {
3314                    Some(item_node)
3315                }
3316            });
3317
3318            if let Some(item_node) = containing_item_node {
3319                return Some(
3320                    Point::from_ts_point(item_node.start_position())
3321                        ..Point::from_ts_point(item_node.end_position()),
3322                );
3323            }
3324
3325            matches.advance();
3326        }
3327        None
3328    }
3329
3330    pub fn outline_items_containing<T: ToOffset>(
3331        &self,
3332        range: Range<T>,
3333        include_extra_context: bool,
3334        theme: Option<&SyntaxTheme>,
3335    ) -> Option<Vec<OutlineItem<Anchor>>> {
3336        let range = range.to_offset(self);
3337        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3338            grammar.outline_config.as_ref().map(|c| &c.query)
3339        });
3340        let configs = matches
3341            .grammars()
3342            .iter()
3343            .map(|g| g.outline_config.as_ref().unwrap())
3344            .collect::<Vec<_>>();
3345
3346        let mut items = Vec::new();
3347        let mut annotation_row_ranges: Vec<Range<u32>> = Vec::new();
3348        while let Some(mat) = matches.peek() {
3349            let config = &configs[mat.grammar_index];
3350            if let Some(item) =
3351                self.next_outline_item(config, &mat, &range, include_extra_context, theme)
3352            {
3353                items.push(item);
3354            } else if let Some(capture) = mat
3355                .captures
3356                .iter()
3357                .find(|capture| Some(capture.index) == config.annotation_capture_ix)
3358            {
3359                let capture_range = capture.node.start_position()..capture.node.end_position();
3360                let mut capture_row_range =
3361                    capture_range.start.row as u32..capture_range.end.row as u32;
3362                if capture_range.end.row > capture_range.start.row && capture_range.end.column == 0
3363                {
3364                    capture_row_range.end -= 1;
3365                }
3366                if let Some(last_row_range) = annotation_row_ranges.last_mut() {
3367                    if last_row_range.end >= capture_row_range.start.saturating_sub(1) {
3368                        last_row_range.end = capture_row_range.end;
3369                    } else {
3370                        annotation_row_ranges.push(capture_row_range);
3371                    }
3372                } else {
3373                    annotation_row_ranges.push(capture_row_range);
3374                }
3375            }
3376            matches.advance();
3377        }
3378
3379        items.sort_by_key(|item| (item.range.start, Reverse(item.range.end)));
3380
3381        // Assign depths based on containment relationships and convert to anchors.
3382        let mut item_ends_stack = Vec::<Point>::new();
3383        let mut anchor_items = Vec::new();
3384        let mut annotation_row_ranges = annotation_row_ranges.into_iter().peekable();
3385        for item in items {
3386            while let Some(last_end) = item_ends_stack.last().copied() {
3387                if last_end < item.range.end {
3388                    item_ends_stack.pop();
3389                } else {
3390                    break;
3391                }
3392            }
3393
3394            let mut annotation_row_range = None;
3395            while let Some(next_annotation_row_range) = annotation_row_ranges.peek() {
3396                let row_preceding_item = item.range.start.row.saturating_sub(1);
3397                if next_annotation_row_range.end < row_preceding_item {
3398                    annotation_row_ranges.next();
3399                } else {
3400                    if next_annotation_row_range.end == row_preceding_item {
3401                        annotation_row_range = Some(next_annotation_row_range.clone());
3402                        annotation_row_ranges.next();
3403                    }
3404                    break;
3405                }
3406            }
3407
3408            anchor_items.push(OutlineItem {
3409                depth: item_ends_stack.len(),
3410                range: self.anchor_after(item.range.start)..self.anchor_before(item.range.end),
3411                text: item.text,
3412                highlight_ranges: item.highlight_ranges,
3413                name_ranges: item.name_ranges,
3414                body_range: item.body_range.map(|body_range| {
3415                    self.anchor_after(body_range.start)..self.anchor_before(body_range.end)
3416                }),
3417                annotation_range: annotation_row_range.map(|annotation_range| {
3418                    self.anchor_after(Point::new(annotation_range.start, 0))
3419                        ..self.anchor_before(Point::new(
3420                            annotation_range.end,
3421                            self.line_len(annotation_range.end),
3422                        ))
3423                }),
3424            });
3425            item_ends_stack.push(item.range.end);
3426        }
3427
3428        Some(anchor_items)
3429    }
3430
3431    fn next_outline_item(
3432        &self,
3433        config: &OutlineConfig,
3434        mat: &SyntaxMapMatch,
3435        range: &Range<usize>,
3436        include_extra_context: bool,
3437        theme: Option<&SyntaxTheme>,
3438    ) -> Option<OutlineItem<Point>> {
3439        let item_node = mat.captures.iter().find_map(|cap| {
3440            if cap.index == config.item_capture_ix {
3441                Some(cap.node)
3442            } else {
3443                None
3444            }
3445        })?;
3446
3447        let item_byte_range = item_node.byte_range();
3448        if item_byte_range.end < range.start || item_byte_range.start > range.end {
3449            return None;
3450        }
3451        let item_point_range = Point::from_ts_point(item_node.start_position())
3452            ..Point::from_ts_point(item_node.end_position());
3453
3454        let mut open_point = None;
3455        let mut close_point = None;
3456        let mut buffer_ranges = Vec::new();
3457        for capture in mat.captures {
3458            let node_is_name;
3459            if capture.index == config.name_capture_ix {
3460                node_is_name = true;
3461            } else if Some(capture.index) == config.context_capture_ix
3462                || (Some(capture.index) == config.extra_context_capture_ix && include_extra_context)
3463            {
3464                node_is_name = false;
3465            } else {
3466                if Some(capture.index) == config.open_capture_ix {
3467                    open_point = Some(Point::from_ts_point(capture.node.end_position()));
3468                } else if Some(capture.index) == config.close_capture_ix {
3469                    close_point = Some(Point::from_ts_point(capture.node.start_position()));
3470                }
3471
3472                continue;
3473            }
3474
3475            let mut range = capture.node.start_byte()..capture.node.end_byte();
3476            let start = capture.node.start_position();
3477            if capture.node.end_position().row > start.row {
3478                range.end = range.start + self.line_len(start.row as u32) as usize - start.column;
3479            }
3480
3481            if !range.is_empty() {
3482                buffer_ranges.push((range, node_is_name));
3483            }
3484        }
3485        if buffer_ranges.is_empty() {
3486            return None;
3487        }
3488        let mut text = String::new();
3489        let mut highlight_ranges = Vec::new();
3490        let mut name_ranges = Vec::new();
3491        let mut chunks = self.chunks(
3492            buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
3493            true,
3494        );
3495        let mut last_buffer_range_end = 0;
3496        for (buffer_range, is_name) in buffer_ranges {
3497            if !text.is_empty() && buffer_range.start > last_buffer_range_end {
3498                text.push(' ');
3499            }
3500            last_buffer_range_end = buffer_range.end;
3501            if is_name {
3502                let mut start = text.len();
3503                let end = start + buffer_range.len();
3504
3505                // When multiple names are captured, then the matchable text
3506                // includes the whitespace in between the names.
3507                if !name_ranges.is_empty() {
3508                    start -= 1;
3509                }
3510
3511                name_ranges.push(start..end);
3512            }
3513
3514            let mut offset = buffer_range.start;
3515            chunks.seek(buffer_range.clone());
3516            for mut chunk in chunks.by_ref() {
3517                if chunk.text.len() > buffer_range.end - offset {
3518                    chunk.text = &chunk.text[0..(buffer_range.end - offset)];
3519                    offset = buffer_range.end;
3520                } else {
3521                    offset += chunk.text.len();
3522                }
3523                let style = chunk
3524                    .syntax_highlight_id
3525                    .zip(theme)
3526                    .and_then(|(highlight, theme)| highlight.style(theme));
3527                if let Some(style) = style {
3528                    let start = text.len();
3529                    let end = start + chunk.text.len();
3530                    highlight_ranges.push((start..end, style));
3531                }
3532                text.push_str(chunk.text);
3533                if offset >= buffer_range.end {
3534                    break;
3535                }
3536            }
3537        }
3538
3539        Some(OutlineItem {
3540            depth: 0, // We'll calculate the depth later
3541            range: item_point_range,
3542            text,
3543            highlight_ranges,
3544            name_ranges,
3545            body_range: open_point.zip(close_point).map(|(start, end)| start..end),
3546            annotation_range: None,
3547        })
3548    }
3549
3550    pub fn function_body_fold_ranges<T: ToOffset>(
3551        &self,
3552        within: Range<T>,
3553    ) -> impl Iterator<Item = Range<usize>> + '_ {
3554        self.text_object_ranges(within, TreeSitterOptions::default())
3555            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
3556    }
3557
3558    /// For each grammar in the language, runs the provided
3559    /// [`tree_sitter::Query`] against the given range.
3560    pub fn matches(
3561        &self,
3562        range: Range<usize>,
3563        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
3564    ) -> SyntaxMapMatches {
3565        self.syntax.matches(range, self, query)
3566    }
3567
3568    /// Returns bracket range pairs overlapping or adjacent to `range`
3569    pub fn bracket_ranges<T: ToOffset>(
3570        &self,
3571        range: Range<T>,
3572    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3573        // Find bracket pairs that *inclusively* contain the given range.
3574        let range = range.start.to_offset(self).saturating_sub(1)
3575            ..self.len().min(range.end.to_offset(self) + 1);
3576
3577        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3578            grammar.brackets_config.as_ref().map(|c| &c.query)
3579        });
3580        let configs = matches
3581            .grammars()
3582            .iter()
3583            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
3584            .collect::<Vec<_>>();
3585
3586        iter::from_fn(move || {
3587            while let Some(mat) = matches.peek() {
3588                let mut open = None;
3589                let mut close = None;
3590                let config = &configs[mat.grammar_index];
3591                for capture in mat.captures {
3592                    if capture.index == config.open_capture_ix {
3593                        open = Some(capture.node.byte_range());
3594                    } else if capture.index == config.close_capture_ix {
3595                        close = Some(capture.node.byte_range());
3596                    }
3597                }
3598
3599                matches.advance();
3600
3601                let Some((open, close)) = open.zip(close) else {
3602                    continue;
3603                };
3604
3605                let bracket_range = open.start..=close.end;
3606                if !bracket_range.overlaps(&range) {
3607                    continue;
3608                }
3609
3610                return Some((open, close));
3611            }
3612            None
3613        })
3614    }
3615
3616    pub fn text_object_ranges<T: ToOffset>(
3617        &self,
3618        range: Range<T>,
3619        options: TreeSitterOptions,
3620    ) -> impl Iterator<Item = (Range<usize>, TextObject)> + '_ {
3621        let range = range.start.to_offset(self).saturating_sub(1)
3622            ..self.len().min(range.end.to_offset(self) + 1);
3623
3624        let mut matches =
3625            self.syntax
3626                .matches_with_options(range.clone(), &self.text, options, |grammar| {
3627                    grammar.text_object_config.as_ref().map(|c| &c.query)
3628                });
3629
3630        let configs = matches
3631            .grammars()
3632            .iter()
3633            .map(|grammar| grammar.text_object_config.as_ref())
3634            .collect::<Vec<_>>();
3635
3636        let mut captures = Vec::<(Range<usize>, TextObject)>::new();
3637
3638        iter::from_fn(move || loop {
3639            while let Some(capture) = captures.pop() {
3640                if capture.0.overlaps(&range) {
3641                    return Some(capture);
3642                }
3643            }
3644
3645            let mat = matches.peek()?;
3646
3647            let Some(config) = configs[mat.grammar_index].as_ref() else {
3648                matches.advance();
3649                continue;
3650            };
3651
3652            for capture in mat.captures {
3653                let Some(ix) = config
3654                    .text_objects_by_capture_ix
3655                    .binary_search_by_key(&capture.index, |e| e.0)
3656                    .ok()
3657                else {
3658                    continue;
3659                };
3660                let text_object = config.text_objects_by_capture_ix[ix].1;
3661                let byte_range = capture.node.byte_range();
3662
3663                let mut found = false;
3664                for (range, existing) in captures.iter_mut() {
3665                    if existing == &text_object {
3666                        range.start = range.start.min(byte_range.start);
3667                        range.end = range.end.max(byte_range.end);
3668                        found = true;
3669                        break;
3670                    }
3671                }
3672
3673                if !found {
3674                    captures.push((byte_range, text_object));
3675                }
3676            }
3677
3678            matches.advance();
3679        })
3680    }
3681
3682    /// Returns enclosing bracket ranges containing the given range
3683    pub fn enclosing_bracket_ranges<T: ToOffset>(
3684        &self,
3685        range: Range<T>,
3686    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3687        let range = range.start.to_offset(self)..range.end.to_offset(self);
3688
3689        self.bracket_ranges(range.clone())
3690            .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
3691    }
3692
3693    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3694    ///
3695    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3696    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3697        &self,
3698        range: Range<T>,
3699        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3700    ) -> Option<(Range<usize>, Range<usize>)> {
3701        let range = range.start.to_offset(self)..range.end.to_offset(self);
3702
3703        // Get the ranges of the innermost pair of brackets.
3704        let mut result: Option<(Range<usize>, Range<usize>)> = None;
3705
3706        for (open, close) in self.enclosing_bracket_ranges(range.clone()) {
3707            if let Some(range_filter) = range_filter {
3708                if !range_filter(open.clone(), close.clone()) {
3709                    continue;
3710                }
3711            }
3712
3713            let len = close.end - open.start;
3714
3715            if let Some((existing_open, existing_close)) = &result {
3716                let existing_len = existing_close.end - existing_open.start;
3717                if len > existing_len {
3718                    continue;
3719                }
3720            }
3721
3722            result = Some((open, close));
3723        }
3724
3725        result
3726    }
3727
3728    /// Returns anchor ranges for any matches of the redaction query.
3729    /// The buffer can be associated with multiple languages, and the redaction query associated with each
3730    /// will be run on the relevant section of the buffer.
3731    pub fn redacted_ranges<T: ToOffset>(
3732        &self,
3733        range: Range<T>,
3734    ) -> impl Iterator<Item = Range<usize>> + '_ {
3735        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3736        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3737            grammar
3738                .redactions_config
3739                .as_ref()
3740                .map(|config| &config.query)
3741        });
3742
3743        let configs = syntax_matches
3744            .grammars()
3745            .iter()
3746            .map(|grammar| grammar.redactions_config.as_ref())
3747            .collect::<Vec<_>>();
3748
3749        iter::from_fn(move || {
3750            let redacted_range = syntax_matches
3751                .peek()
3752                .and_then(|mat| {
3753                    configs[mat.grammar_index].and_then(|config| {
3754                        mat.captures
3755                            .iter()
3756                            .find(|capture| capture.index == config.redaction_capture_ix)
3757                    })
3758                })
3759                .map(|mat| mat.node.byte_range());
3760            syntax_matches.advance();
3761            redacted_range
3762        })
3763    }
3764
3765    pub fn injections_intersecting_range<T: ToOffset>(
3766        &self,
3767        range: Range<T>,
3768    ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3769        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3770
3771        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3772            grammar
3773                .injection_config
3774                .as_ref()
3775                .map(|config| &config.query)
3776        });
3777
3778        let configs = syntax_matches
3779            .grammars()
3780            .iter()
3781            .map(|grammar| grammar.injection_config.as_ref())
3782            .collect::<Vec<_>>();
3783
3784        iter::from_fn(move || {
3785            let ranges = syntax_matches.peek().and_then(|mat| {
3786                let config = &configs[mat.grammar_index]?;
3787                let content_capture_range = mat.captures.iter().find_map(|capture| {
3788                    if capture.index == config.content_capture_ix {
3789                        Some(capture.node.byte_range())
3790                    } else {
3791                        None
3792                    }
3793                })?;
3794                let language = self.language_at(content_capture_range.start)?;
3795                Some((content_capture_range, language))
3796            });
3797            syntax_matches.advance();
3798            ranges
3799        })
3800    }
3801
3802    pub fn runnable_ranges(
3803        &self,
3804        offset_range: Range<usize>,
3805    ) -> impl Iterator<Item = RunnableRange> + '_ {
3806        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3807            grammar.runnable_config.as_ref().map(|config| &config.query)
3808        });
3809
3810        let test_configs = syntax_matches
3811            .grammars()
3812            .iter()
3813            .map(|grammar| grammar.runnable_config.as_ref())
3814            .collect::<Vec<_>>();
3815
3816        iter::from_fn(move || loop {
3817            let mat = syntax_matches.peek()?;
3818
3819            let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3820                let mut run_range = None;
3821                let full_range = mat.captures.iter().fold(
3822                    Range {
3823                        start: usize::MAX,
3824                        end: 0,
3825                    },
3826                    |mut acc, next| {
3827                        let byte_range = next.node.byte_range();
3828                        if acc.start > byte_range.start {
3829                            acc.start = byte_range.start;
3830                        }
3831                        if acc.end < byte_range.end {
3832                            acc.end = byte_range.end;
3833                        }
3834                        acc
3835                    },
3836                );
3837                if full_range.start > full_range.end {
3838                    // We did not find a full spanning range of this match.
3839                    return None;
3840                }
3841                let extra_captures: SmallVec<[_; 1]> =
3842                    SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3843                        test_configs
3844                            .extra_captures
3845                            .get(capture.index as usize)
3846                            .cloned()
3847                            .and_then(|tag_name| match tag_name {
3848                                RunnableCapture::Named(name) => {
3849                                    Some((capture.node.byte_range(), name))
3850                                }
3851                                RunnableCapture::Run => {
3852                                    let _ = run_range.insert(capture.node.byte_range());
3853                                    None
3854                                }
3855                            })
3856                    }));
3857                let run_range = run_range?;
3858                let tags = test_configs
3859                    .query
3860                    .property_settings(mat.pattern_index)
3861                    .iter()
3862                    .filter_map(|property| {
3863                        if *property.key == *"tag" {
3864                            property
3865                                .value
3866                                .as_ref()
3867                                .map(|value| RunnableTag(value.to_string().into()))
3868                        } else {
3869                            None
3870                        }
3871                    })
3872                    .collect();
3873                let extra_captures = extra_captures
3874                    .into_iter()
3875                    .map(|(range, name)| {
3876                        (
3877                            name.to_string(),
3878                            self.text_for_range(range.clone()).collect::<String>(),
3879                        )
3880                    })
3881                    .collect();
3882                // All tags should have the same range.
3883                Some(RunnableRange {
3884                    run_range,
3885                    full_range,
3886                    runnable: Runnable {
3887                        tags,
3888                        language: mat.language,
3889                        buffer: self.remote_id(),
3890                    },
3891                    extra_captures,
3892                    buffer_id: self.remote_id(),
3893                })
3894            });
3895
3896            syntax_matches.advance();
3897            if test_range.is_some() {
3898                // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
3899                // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
3900                return test_range;
3901            }
3902        })
3903    }
3904
3905    /// Returns selections for remote peers intersecting the given range.
3906    #[allow(clippy::type_complexity)]
3907    pub fn selections_in_range(
3908        &self,
3909        range: Range<Anchor>,
3910        include_local: bool,
3911    ) -> impl Iterator<
3912        Item = (
3913            ReplicaId,
3914            bool,
3915            CursorShape,
3916            impl Iterator<Item = &Selection<Anchor>> + '_,
3917        ),
3918    > + '_ {
3919        self.remote_selections
3920            .iter()
3921            .filter(move |(replica_id, set)| {
3922                (include_local || **replica_id != self.text.replica_id())
3923                    && !set.selections.is_empty()
3924            })
3925            .map(move |(replica_id, set)| {
3926                let start_ix = match set.selections.binary_search_by(|probe| {
3927                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
3928                }) {
3929                    Ok(ix) | Err(ix) => ix,
3930                };
3931                let end_ix = match set.selections.binary_search_by(|probe| {
3932                    probe.start.cmp(&range.end, self).then(Ordering::Less)
3933                }) {
3934                    Ok(ix) | Err(ix) => ix,
3935                };
3936
3937                (
3938                    *replica_id,
3939                    set.line_mode,
3940                    set.cursor_shape,
3941                    set.selections[start_ix..end_ix].iter(),
3942                )
3943            })
3944    }
3945
3946    /// Returns if the buffer contains any diagnostics.
3947    pub fn has_diagnostics(&self) -> bool {
3948        !self.diagnostics.is_empty()
3949    }
3950
3951    /// Returns all the diagnostics intersecting the given range.
3952    pub fn diagnostics_in_range<'a, T, O>(
3953        &'a self,
3954        search_range: Range<T>,
3955        reversed: bool,
3956    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3957    where
3958        T: 'a + Clone + ToOffset,
3959        O: 'a + FromAnchor,
3960    {
3961        let mut iterators: Vec<_> = self
3962            .diagnostics
3963            .iter()
3964            .map(|(_, collection)| {
3965                collection
3966                    .range::<T, text::Anchor>(search_range.clone(), self, true, reversed)
3967                    .peekable()
3968            })
3969            .collect();
3970
3971        std::iter::from_fn(move || {
3972            let (next_ix, _) = iterators
3973                .iter_mut()
3974                .enumerate()
3975                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
3976                .min_by(|(_, a), (_, b)| {
3977                    let cmp = a
3978                        .range
3979                        .start
3980                        .cmp(&b.range.start, self)
3981                        // when range is equal, sort by diagnostic severity
3982                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
3983                        // and stabilize order with group_id
3984                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
3985                    if reversed {
3986                        cmp.reverse()
3987                    } else {
3988                        cmp
3989                    }
3990                })?;
3991            iterators[next_ix]
3992                .next()
3993                .map(|DiagnosticEntry { range, diagnostic }| DiagnosticEntry {
3994                    diagnostic,
3995                    range: FromAnchor::from_anchor(&range.start, self)
3996                        ..FromAnchor::from_anchor(&range.end, self),
3997                })
3998        })
3999    }
4000
4001    /// Returns all the diagnostic groups associated with the given
4002    /// language server ID. If no language server ID is provided,
4003    /// all diagnostics groups are returned.
4004    pub fn diagnostic_groups(
4005        &self,
4006        language_server_id: Option<LanguageServerId>,
4007    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
4008        let mut groups = Vec::new();
4009
4010        if let Some(language_server_id) = language_server_id {
4011            if let Ok(ix) = self
4012                .diagnostics
4013                .binary_search_by_key(&language_server_id, |e| e.0)
4014            {
4015                self.diagnostics[ix]
4016                    .1
4017                    .groups(language_server_id, &mut groups, self);
4018            }
4019        } else {
4020            for (language_server_id, diagnostics) in self.diagnostics.iter() {
4021                diagnostics.groups(*language_server_id, &mut groups, self);
4022            }
4023        }
4024
4025        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
4026            let a_start = &group_a.entries[group_a.primary_ix].range.start;
4027            let b_start = &group_b.entries[group_b.primary_ix].range.start;
4028            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
4029        });
4030
4031        groups
4032    }
4033
4034    /// Returns an iterator over the diagnostics for the given group.
4035    pub fn diagnostic_group<O>(
4036        &self,
4037        group_id: usize,
4038    ) -> impl Iterator<Item = DiagnosticEntry<O>> + '_
4039    where
4040        O: FromAnchor + 'static,
4041    {
4042        self.diagnostics
4043            .iter()
4044            .flat_map(move |(_, set)| set.group(group_id, self))
4045    }
4046
4047    /// An integer version number that accounts for all updates besides
4048    /// the buffer's text itself (which is versioned via a version vector).
4049    pub fn non_text_state_update_count(&self) -> usize {
4050        self.non_text_state_update_count
4051    }
4052
4053    /// Returns a snapshot of underlying file.
4054    pub fn file(&self) -> Option<&Arc<dyn File>> {
4055        self.file.as_ref()
4056    }
4057
4058    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
4059    pub fn resolve_file_path(&self, cx: &App, include_root: bool) -> Option<PathBuf> {
4060        if let Some(file) = self.file() {
4061            if file.path().file_name().is_none() || include_root {
4062                Some(file.full_path(cx))
4063            } else {
4064                Some(file.path().to_path_buf())
4065            }
4066        } else {
4067            None
4068        }
4069    }
4070}
4071
4072fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
4073    indent_size_for_text(text.chars_at(Point::new(row, 0)))
4074}
4075
4076fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
4077    let mut result = IndentSize::spaces(0);
4078    for c in text {
4079        let kind = match c {
4080            ' ' => IndentKind::Space,
4081            '\t' => IndentKind::Tab,
4082            _ => break,
4083        };
4084        if result.len == 0 {
4085            result.kind = kind;
4086        }
4087        result.len += 1;
4088    }
4089    result
4090}
4091
4092impl Clone for BufferSnapshot {
4093    fn clone(&self) -> Self {
4094        Self {
4095            text: self.text.clone(),
4096            syntax: self.syntax.clone(),
4097            file: self.file.clone(),
4098            remote_selections: self.remote_selections.clone(),
4099            diagnostics: self.diagnostics.clone(),
4100            language: self.language.clone(),
4101            non_text_state_update_count: self.non_text_state_update_count,
4102        }
4103    }
4104}
4105
4106impl Deref for BufferSnapshot {
4107    type Target = text::BufferSnapshot;
4108
4109    fn deref(&self) -> &Self::Target {
4110        &self.text
4111    }
4112}
4113
4114unsafe impl<'a> Send for BufferChunks<'a> {}
4115
4116impl<'a> BufferChunks<'a> {
4117    pub(crate) fn new(
4118        text: &'a Rope,
4119        range: Range<usize>,
4120        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
4121        diagnostics: bool,
4122        buffer_snapshot: Option<&'a BufferSnapshot>,
4123    ) -> Self {
4124        let mut highlights = None;
4125        if let Some((captures, highlight_maps)) = syntax {
4126            highlights = Some(BufferChunkHighlights {
4127                captures,
4128                next_capture: None,
4129                stack: Default::default(),
4130                highlight_maps,
4131            })
4132        }
4133
4134        let diagnostic_endpoints = diagnostics.then(|| Vec::new().into_iter().peekable());
4135        let chunks = text.chunks_in_range(range.clone());
4136
4137        let mut this = BufferChunks {
4138            range,
4139            buffer_snapshot,
4140            chunks,
4141            diagnostic_endpoints,
4142            error_depth: 0,
4143            warning_depth: 0,
4144            information_depth: 0,
4145            hint_depth: 0,
4146            unnecessary_depth: 0,
4147            highlights,
4148        };
4149        this.initialize_diagnostic_endpoints();
4150        this
4151    }
4152
4153    /// Seeks to the given byte offset in the buffer.
4154    pub fn seek(&mut self, range: Range<usize>) {
4155        let old_range = std::mem::replace(&mut self.range, range.clone());
4156        self.chunks.set_range(self.range.clone());
4157        if let Some(highlights) = self.highlights.as_mut() {
4158            if old_range.start <= self.range.start && old_range.end >= self.range.end {
4159                // Reuse existing highlights stack, as the new range is a subrange of the old one.
4160                highlights
4161                    .stack
4162                    .retain(|(end_offset, _)| *end_offset > range.start);
4163                if let Some(capture) = &highlights.next_capture {
4164                    if range.start >= capture.node.start_byte() {
4165                        let next_capture_end = capture.node.end_byte();
4166                        if range.start < next_capture_end {
4167                            highlights.stack.push((
4168                                next_capture_end,
4169                                highlights.highlight_maps[capture.grammar_index].get(capture.index),
4170                            ));
4171                        }
4172                        highlights.next_capture.take();
4173                    }
4174                }
4175            } else if let Some(snapshot) = self.buffer_snapshot {
4176                let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
4177                *highlights = BufferChunkHighlights {
4178                    captures,
4179                    next_capture: None,
4180                    stack: Default::default(),
4181                    highlight_maps,
4182                };
4183            } else {
4184                // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
4185                // Seeking such BufferChunks is not supported.
4186                debug_assert!(false, "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot");
4187            }
4188
4189            highlights.captures.set_byte_range(self.range.clone());
4190            self.initialize_diagnostic_endpoints();
4191        }
4192    }
4193
4194    fn initialize_diagnostic_endpoints(&mut self) {
4195        if let Some(diagnostics) = self.diagnostic_endpoints.as_mut() {
4196            if let Some(buffer) = self.buffer_snapshot {
4197                let mut diagnostic_endpoints = Vec::new();
4198                for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
4199                    diagnostic_endpoints.push(DiagnosticEndpoint {
4200                        offset: entry.range.start,
4201                        is_start: true,
4202                        severity: entry.diagnostic.severity,
4203                        is_unnecessary: entry.diagnostic.is_unnecessary,
4204                    });
4205                    diagnostic_endpoints.push(DiagnosticEndpoint {
4206                        offset: entry.range.end,
4207                        is_start: false,
4208                        severity: entry.diagnostic.severity,
4209                        is_unnecessary: entry.diagnostic.is_unnecessary,
4210                    });
4211                }
4212                diagnostic_endpoints
4213                    .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
4214                *diagnostics = diagnostic_endpoints.into_iter().peekable();
4215                self.hint_depth = 0;
4216                self.error_depth = 0;
4217                self.warning_depth = 0;
4218                self.information_depth = 0;
4219            }
4220        }
4221    }
4222
4223    /// The current byte offset in the buffer.
4224    pub fn offset(&self) -> usize {
4225        self.range.start
4226    }
4227
4228    pub fn range(&self) -> Range<usize> {
4229        self.range.clone()
4230    }
4231
4232    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
4233        let depth = match endpoint.severity {
4234            DiagnosticSeverity::ERROR => &mut self.error_depth,
4235            DiagnosticSeverity::WARNING => &mut self.warning_depth,
4236            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
4237            DiagnosticSeverity::HINT => &mut self.hint_depth,
4238            _ => return,
4239        };
4240        if endpoint.is_start {
4241            *depth += 1;
4242        } else {
4243            *depth -= 1;
4244        }
4245
4246        if endpoint.is_unnecessary {
4247            if endpoint.is_start {
4248                self.unnecessary_depth += 1;
4249            } else {
4250                self.unnecessary_depth -= 1;
4251            }
4252        }
4253    }
4254
4255    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
4256        if self.error_depth > 0 {
4257            Some(DiagnosticSeverity::ERROR)
4258        } else if self.warning_depth > 0 {
4259            Some(DiagnosticSeverity::WARNING)
4260        } else if self.information_depth > 0 {
4261            Some(DiagnosticSeverity::INFORMATION)
4262        } else if self.hint_depth > 0 {
4263            Some(DiagnosticSeverity::HINT)
4264        } else {
4265            None
4266        }
4267    }
4268
4269    fn current_code_is_unnecessary(&self) -> bool {
4270        self.unnecessary_depth > 0
4271    }
4272}
4273
4274impl<'a> Iterator for BufferChunks<'a> {
4275    type Item = Chunk<'a>;
4276
4277    fn next(&mut self) -> Option<Self::Item> {
4278        let mut next_capture_start = usize::MAX;
4279        let mut next_diagnostic_endpoint = usize::MAX;
4280
4281        if let Some(highlights) = self.highlights.as_mut() {
4282            while let Some((parent_capture_end, _)) = highlights.stack.last() {
4283                if *parent_capture_end <= self.range.start {
4284                    highlights.stack.pop();
4285                } else {
4286                    break;
4287                }
4288            }
4289
4290            if highlights.next_capture.is_none() {
4291                highlights.next_capture = highlights.captures.next();
4292            }
4293
4294            while let Some(capture) = highlights.next_capture.as_ref() {
4295                if self.range.start < capture.node.start_byte() {
4296                    next_capture_start = capture.node.start_byte();
4297                    break;
4298                } else {
4299                    let highlight_id =
4300                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
4301                    highlights
4302                        .stack
4303                        .push((capture.node.end_byte(), highlight_id));
4304                    highlights.next_capture = highlights.captures.next();
4305                }
4306            }
4307        }
4308
4309        let mut diagnostic_endpoints = std::mem::take(&mut self.diagnostic_endpoints);
4310        if let Some(diagnostic_endpoints) = diagnostic_endpoints.as_mut() {
4311            while let Some(endpoint) = diagnostic_endpoints.peek().copied() {
4312                if endpoint.offset <= self.range.start {
4313                    self.update_diagnostic_depths(endpoint);
4314                    diagnostic_endpoints.next();
4315                } else {
4316                    next_diagnostic_endpoint = endpoint.offset;
4317                    break;
4318                }
4319            }
4320        }
4321        self.diagnostic_endpoints = diagnostic_endpoints;
4322
4323        if let Some(chunk) = self.chunks.peek() {
4324            let chunk_start = self.range.start;
4325            let mut chunk_end = (self.chunks.offset() + chunk.len())
4326                .min(next_capture_start)
4327                .min(next_diagnostic_endpoint);
4328            let mut highlight_id = None;
4329            if let Some(highlights) = self.highlights.as_ref() {
4330                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
4331                    chunk_end = chunk_end.min(*parent_capture_end);
4332                    highlight_id = Some(*parent_highlight_id);
4333                }
4334            }
4335
4336            let slice =
4337                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
4338            self.range.start = chunk_end;
4339            if self.range.start == self.chunks.offset() + chunk.len() {
4340                self.chunks.next().unwrap();
4341            }
4342
4343            Some(Chunk {
4344                text: slice,
4345                syntax_highlight_id: highlight_id,
4346                diagnostic_severity: self.current_diagnostic_severity(),
4347                is_unnecessary: self.current_code_is_unnecessary(),
4348                ..Default::default()
4349            })
4350        } else {
4351            None
4352        }
4353    }
4354}
4355
4356impl operation_queue::Operation for Operation {
4357    fn lamport_timestamp(&self) -> clock::Lamport {
4358        match self {
4359            Operation::Buffer(_) => {
4360                unreachable!("buffer operations should never be deferred at this layer")
4361            }
4362            Operation::UpdateDiagnostics {
4363                lamport_timestamp, ..
4364            }
4365            | Operation::UpdateSelections {
4366                lamport_timestamp, ..
4367            }
4368            | Operation::UpdateCompletionTriggers {
4369                lamport_timestamp, ..
4370            } => *lamport_timestamp,
4371        }
4372    }
4373}
4374
4375impl Default for Diagnostic {
4376    fn default() -> Self {
4377        Self {
4378            source: Default::default(),
4379            code: None,
4380            severity: DiagnosticSeverity::ERROR,
4381            message: Default::default(),
4382            group_id: 0,
4383            is_primary: false,
4384            is_disk_based: false,
4385            is_unnecessary: false,
4386            data: None,
4387        }
4388    }
4389}
4390
4391impl IndentSize {
4392    /// Returns an [`IndentSize`] representing the given spaces.
4393    pub fn spaces(len: u32) -> Self {
4394        Self {
4395            len,
4396            kind: IndentKind::Space,
4397        }
4398    }
4399
4400    /// Returns an [`IndentSize`] representing a tab.
4401    pub fn tab() -> Self {
4402        Self {
4403            len: 1,
4404            kind: IndentKind::Tab,
4405        }
4406    }
4407
4408    /// An iterator over the characters represented by this [`IndentSize`].
4409    pub fn chars(&self) -> impl Iterator<Item = char> {
4410        iter::repeat(self.char()).take(self.len as usize)
4411    }
4412
4413    /// The character representation of this [`IndentSize`].
4414    pub fn char(&self) -> char {
4415        match self.kind {
4416            IndentKind::Space => ' ',
4417            IndentKind::Tab => '\t',
4418        }
4419    }
4420
4421    /// Consumes the current [`IndentSize`] and returns a new one that has
4422    /// been shrunk or enlarged by the given size along the given direction.
4423    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4424        match direction {
4425            Ordering::Less => {
4426                if self.kind == size.kind && self.len >= size.len {
4427                    self.len -= size.len;
4428                }
4429            }
4430            Ordering::Equal => {}
4431            Ordering::Greater => {
4432                if self.len == 0 {
4433                    self = size;
4434                } else if self.kind == size.kind {
4435                    self.len += size.len;
4436                }
4437            }
4438        }
4439        self
4440    }
4441
4442    pub fn len_with_expanded_tabs(&self, tab_size: NonZeroU32) -> usize {
4443        match self.kind {
4444            IndentKind::Space => self.len as usize,
4445            IndentKind::Tab => self.len as usize * tab_size.get() as usize,
4446        }
4447    }
4448}
4449
4450#[cfg(any(test, feature = "test-support"))]
4451pub struct TestFile {
4452    pub path: Arc<Path>,
4453    pub root_name: String,
4454}
4455
4456#[cfg(any(test, feature = "test-support"))]
4457impl File for TestFile {
4458    fn path(&self) -> &Arc<Path> {
4459        &self.path
4460    }
4461
4462    fn full_path(&self, _: &gpui::App) -> PathBuf {
4463        PathBuf::from(&self.root_name).join(self.path.as_ref())
4464    }
4465
4466    fn as_local(&self) -> Option<&dyn LocalFile> {
4467        None
4468    }
4469
4470    fn disk_state(&self) -> DiskState {
4471        unimplemented!()
4472    }
4473
4474    fn file_name<'a>(&'a self, _: &'a gpui::App) -> &'a std::ffi::OsStr {
4475        self.path().file_name().unwrap_or(self.root_name.as_ref())
4476    }
4477
4478    fn worktree_id(&self, _: &App) -> WorktreeId {
4479        WorktreeId::from_usize(0)
4480    }
4481
4482    fn as_any(&self) -> &dyn std::any::Any {
4483        unimplemented!()
4484    }
4485
4486    fn to_proto(&self, _: &App) -> rpc::proto::File {
4487        unimplemented!()
4488    }
4489
4490    fn is_private(&self) -> bool {
4491        false
4492    }
4493}
4494
4495pub(crate) fn contiguous_ranges(
4496    values: impl Iterator<Item = u32>,
4497    max_len: usize,
4498) -> impl Iterator<Item = Range<u32>> {
4499    let mut values = values;
4500    let mut current_range: Option<Range<u32>> = None;
4501    std::iter::from_fn(move || loop {
4502        if let Some(value) = values.next() {
4503            if let Some(range) = &mut current_range {
4504                if value == range.end && range.len() < max_len {
4505                    range.end += 1;
4506                    continue;
4507                }
4508            }
4509
4510            let prev_range = current_range.clone();
4511            current_range = Some(value..(value + 1));
4512            if prev_range.is_some() {
4513                return prev_range;
4514            }
4515        } else {
4516            return current_range.take();
4517        }
4518    })
4519}
4520
4521#[derive(Default, Debug)]
4522pub struct CharClassifier {
4523    scope: Option<LanguageScope>,
4524    for_completion: bool,
4525    ignore_punctuation: bool,
4526}
4527
4528impl CharClassifier {
4529    pub fn new(scope: Option<LanguageScope>) -> Self {
4530        Self {
4531            scope,
4532            for_completion: false,
4533            ignore_punctuation: false,
4534        }
4535    }
4536
4537    pub fn for_completion(self, for_completion: bool) -> Self {
4538        Self {
4539            for_completion,
4540            ..self
4541        }
4542    }
4543
4544    pub fn ignore_punctuation(self, ignore_punctuation: bool) -> Self {
4545        Self {
4546            ignore_punctuation,
4547            ..self
4548        }
4549    }
4550
4551    pub fn is_whitespace(&self, c: char) -> bool {
4552        self.kind(c) == CharKind::Whitespace
4553    }
4554
4555    pub fn is_word(&self, c: char) -> bool {
4556        self.kind(c) == CharKind::Word
4557    }
4558
4559    pub fn is_punctuation(&self, c: char) -> bool {
4560        self.kind(c) == CharKind::Punctuation
4561    }
4562
4563    pub fn kind_with(&self, c: char, ignore_punctuation: bool) -> CharKind {
4564        if c.is_whitespace() {
4565            return CharKind::Whitespace;
4566        } else if c.is_alphanumeric() || c == '_' {
4567            return CharKind::Word;
4568        }
4569
4570        if let Some(scope) = &self.scope {
4571            if let Some(characters) = scope.word_characters() {
4572                if characters.contains(&c) {
4573                    if c == '-' && !self.for_completion && !ignore_punctuation {
4574                        return CharKind::Punctuation;
4575                    }
4576                    return CharKind::Word;
4577                }
4578            }
4579        }
4580
4581        if ignore_punctuation {
4582            CharKind::Word
4583        } else {
4584            CharKind::Punctuation
4585        }
4586    }
4587
4588    pub fn kind(&self, c: char) -> CharKind {
4589        self.kind_with(c, self.ignore_punctuation)
4590    }
4591}
4592
4593/// Find all of the ranges of whitespace that occur at the ends of lines
4594/// in the given rope.
4595///
4596/// This could also be done with a regex search, but this implementation
4597/// avoids copying text.
4598pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4599    let mut ranges = Vec::new();
4600
4601    let mut offset = 0;
4602    let mut prev_chunk_trailing_whitespace_range = 0..0;
4603    for chunk in rope.chunks() {
4604        let mut prev_line_trailing_whitespace_range = 0..0;
4605        for (i, line) in chunk.split('\n').enumerate() {
4606            let line_end_offset = offset + line.len();
4607            let trimmed_line_len = line.trim_end_matches([' ', '\t']).len();
4608            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4609
4610            if i == 0 && trimmed_line_len == 0 {
4611                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4612            }
4613            if !prev_line_trailing_whitespace_range.is_empty() {
4614                ranges.push(prev_line_trailing_whitespace_range);
4615            }
4616
4617            offset = line_end_offset + 1;
4618            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4619        }
4620
4621        offset -= 1;
4622        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4623    }
4624
4625    if !prev_chunk_trailing_whitespace_range.is_empty() {
4626        ranges.push(prev_chunk_trailing_whitespace_range);
4627    }
4628
4629    ranges
4630}