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, NumberOrString};
  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, Serialize, Deserialize)]
 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<NumberOrString>,
 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    pub fn build_empty_snapshot(cx: &mut App) -> BufferSnapshot {
1005        let entity_id = cx.reserve_entity::<Self>().entity_id();
1006        let buffer_id = entity_id.as_non_zero_u64().into();
1007        let text =
1008            TextBuffer::new_normalized(0, buffer_id, Default::default(), Rope::new()).snapshot();
1009        let syntax = SyntaxMap::new(&text).snapshot();
1010        BufferSnapshot {
1011            text,
1012            syntax,
1013            file: None,
1014            diagnostics: Default::default(),
1015            remote_selections: Default::default(),
1016            language: None,
1017            non_text_state_update_count: 0,
1018        }
1019    }
1020
1021    #[cfg(any(test, feature = "test-support"))]
1022    pub fn build_snapshot_sync(
1023        text: Rope,
1024        language: Option<Arc<Language>>,
1025        language_registry: Option<Arc<LanguageRegistry>>,
1026        cx: &mut App,
1027    ) -> BufferSnapshot {
1028        let entity_id = cx.reserve_entity::<Self>().entity_id();
1029        let buffer_id = entity_id.as_non_zero_u64().into();
1030        let text = TextBuffer::new_normalized(0, buffer_id, Default::default(), text).snapshot();
1031        let mut syntax = SyntaxMap::new(&text).snapshot();
1032        if let Some(language) = language.clone() {
1033            let text = text.clone();
1034            let language = language.clone();
1035            let language_registry = language_registry.clone();
1036            syntax.reparse(&text, language_registry, language);
1037        }
1038        BufferSnapshot {
1039            text,
1040            syntax,
1041            file: None,
1042            diagnostics: Default::default(),
1043            remote_selections: Default::default(),
1044            language,
1045            non_text_state_update_count: 0,
1046        }
1047    }
1048
1049    /// Retrieve a snapshot of the buffer's current state. This is computationally
1050    /// cheap, and allows reading from the buffer on a background thread.
1051    pub fn snapshot(&self) -> BufferSnapshot {
1052        let text = self.text.snapshot();
1053        let mut syntax_map = self.syntax_map.lock();
1054        syntax_map.interpolate(&text);
1055        let syntax = syntax_map.snapshot();
1056
1057        BufferSnapshot {
1058            text,
1059            syntax,
1060            file: self.file.clone(),
1061            remote_selections: self.remote_selections.clone(),
1062            diagnostics: self.diagnostics.clone(),
1063            language: self.language.clone(),
1064            non_text_state_update_count: self.non_text_state_update_count,
1065        }
1066    }
1067
1068    pub fn branch(&mut self, cx: &mut Context<Self>) -> Entity<Self> {
1069        let this = cx.entity();
1070        cx.new(|cx| {
1071            let mut branch = Self {
1072                branch_state: Some(BufferBranchState {
1073                    base_buffer: this.clone(),
1074                    merged_operations: Default::default(),
1075                }),
1076                language: self.language.clone(),
1077                has_conflict: self.has_conflict,
1078                has_unsaved_edits: Cell::new(self.has_unsaved_edits.get_mut().clone()),
1079                _subscriptions: vec![cx.subscribe(&this, Self::on_base_buffer_event)],
1080                ..Self::build(self.text.branch(), self.file.clone(), self.capability())
1081            };
1082            if let Some(language_registry) = self.language_registry() {
1083                branch.set_language_registry(language_registry);
1084            }
1085
1086            // Reparse the branch buffer so that we get syntax highlighting immediately.
1087            branch.reparse(cx);
1088
1089            branch
1090        })
1091    }
1092
1093    pub fn preview_edits(
1094        &self,
1095        edits: Arc<[(Range<Anchor>, String)]>,
1096        cx: &App,
1097    ) -> Task<EditPreview> {
1098        let registry = self.language_registry();
1099        let language = self.language().cloned();
1100        let old_snapshot = self.text.snapshot();
1101        let mut branch_buffer = self.text.branch();
1102        let mut syntax_snapshot = self.syntax_map.lock().snapshot();
1103        cx.background_executor().spawn(async move {
1104            if !edits.is_empty() {
1105                if let Some(language) = language.clone() {
1106                    syntax_snapshot.reparse(&old_snapshot, registry.clone(), language);
1107                }
1108
1109                branch_buffer.edit(edits.iter().cloned());
1110                let snapshot = branch_buffer.snapshot();
1111                syntax_snapshot.interpolate(&snapshot);
1112
1113                if let Some(language) = language {
1114                    syntax_snapshot.reparse(&snapshot, registry, language);
1115                }
1116            }
1117            EditPreview {
1118                old_snapshot,
1119                applied_edits_snapshot: branch_buffer.snapshot(),
1120                syntax_snapshot,
1121            }
1122        })
1123    }
1124
1125    /// Applies all of the changes in this buffer that intersect any of the
1126    /// given `ranges` to its base buffer.
1127    ///
1128    /// If `ranges` is empty, then all changes will be applied. This buffer must
1129    /// be a branch buffer to call this method.
1130    pub fn merge_into_base(&mut self, ranges: Vec<Range<usize>>, cx: &mut Context<Self>) {
1131        let Some(base_buffer) = self.base_buffer() else {
1132            debug_panic!("not a branch buffer");
1133            return;
1134        };
1135
1136        let mut ranges = if ranges.is_empty() {
1137            &[0..usize::MAX]
1138        } else {
1139            ranges.as_slice()
1140        }
1141        .into_iter()
1142        .peekable();
1143
1144        let mut edits = Vec::new();
1145        for edit in self.edits_since::<usize>(&base_buffer.read(cx).version()) {
1146            let mut is_included = false;
1147            while let Some(range) = ranges.peek() {
1148                if range.end < edit.new.start {
1149                    ranges.next().unwrap();
1150                } else {
1151                    if range.start <= edit.new.end {
1152                        is_included = true;
1153                    }
1154                    break;
1155                }
1156            }
1157
1158            if is_included {
1159                edits.push((
1160                    edit.old.clone(),
1161                    self.text_for_range(edit.new.clone()).collect::<String>(),
1162                ));
1163            }
1164        }
1165
1166        let operation = base_buffer.update(cx, |base_buffer, cx| {
1167            // cx.emit(BufferEvent::DiffBaseChanged);
1168            base_buffer.edit(edits, None, cx)
1169        });
1170
1171        if let Some(operation) = operation {
1172            if let Some(BufferBranchState {
1173                merged_operations, ..
1174            }) = &mut self.branch_state
1175            {
1176                merged_operations.push(operation);
1177            }
1178        }
1179    }
1180
1181    fn on_base_buffer_event(
1182        &mut self,
1183        _: Entity<Buffer>,
1184        event: &BufferEvent,
1185        cx: &mut Context<Self>,
1186    ) {
1187        let BufferEvent::Operation { operation, .. } = event else {
1188            return;
1189        };
1190        let Some(BufferBranchState {
1191            merged_operations, ..
1192        }) = &mut self.branch_state
1193        else {
1194            return;
1195        };
1196
1197        let mut operation_to_undo = None;
1198        if let Operation::Buffer(text::Operation::Edit(operation)) = &operation {
1199            if let Ok(ix) = merged_operations.binary_search(&operation.timestamp) {
1200                merged_operations.remove(ix);
1201                operation_to_undo = Some(operation.timestamp);
1202            }
1203        }
1204
1205        self.apply_ops([operation.clone()], cx);
1206
1207        if let Some(timestamp) = operation_to_undo {
1208            let counts = [(timestamp, u32::MAX)].into_iter().collect();
1209            self.undo_operations(counts, cx);
1210        }
1211    }
1212
1213    #[cfg(test)]
1214    pub(crate) fn as_text_snapshot(&self) -> &text::BufferSnapshot {
1215        &self.text
1216    }
1217
1218    /// Retrieve a snapshot of the buffer's raw text, without any
1219    /// language-related state like the syntax tree or diagnostics.
1220    pub fn text_snapshot(&self) -> text::BufferSnapshot {
1221        self.text.snapshot()
1222    }
1223
1224    /// The file associated with the buffer, if any.
1225    pub fn file(&self) -> Option<&Arc<dyn File>> {
1226        self.file.as_ref()
1227    }
1228
1229    /// The version of the buffer that was last saved or reloaded from disk.
1230    pub fn saved_version(&self) -> &clock::Global {
1231        &self.saved_version
1232    }
1233
1234    /// The mtime of the buffer's file when the buffer was last saved or reloaded from disk.
1235    pub fn saved_mtime(&self) -> Option<MTime> {
1236        self.saved_mtime
1237    }
1238
1239    /// Assign a language to the buffer.
1240    pub fn set_language(&mut self, language: Option<Arc<Language>>, cx: &mut Context<Self>) {
1241        self.non_text_state_update_count += 1;
1242        self.syntax_map.lock().clear(&self.text);
1243        self.language = language;
1244        self.reparse(cx);
1245        cx.emit(BufferEvent::LanguageChanged);
1246    }
1247
1248    /// Assign a language registry to the buffer. This allows the buffer to retrieve
1249    /// other languages if parts of the buffer are written in different languages.
1250    pub fn set_language_registry(&self, language_registry: Arc<LanguageRegistry>) {
1251        self.syntax_map
1252            .lock()
1253            .set_language_registry(language_registry);
1254    }
1255
1256    pub fn language_registry(&self) -> Option<Arc<LanguageRegistry>> {
1257        self.syntax_map.lock().language_registry()
1258    }
1259
1260    /// Assign the buffer a new [`Capability`].
1261    pub fn set_capability(&mut self, capability: Capability, cx: &mut Context<Self>) {
1262        self.capability = capability;
1263        cx.emit(BufferEvent::CapabilityChanged)
1264    }
1265
1266    /// This method is called to signal that the buffer has been saved.
1267    pub fn did_save(
1268        &mut self,
1269        version: clock::Global,
1270        mtime: Option<MTime>,
1271        cx: &mut Context<Self>,
1272    ) {
1273        self.saved_version = version;
1274        self.has_unsaved_edits
1275            .set((self.saved_version().clone(), false));
1276        self.has_conflict = false;
1277        self.saved_mtime = mtime;
1278        cx.emit(BufferEvent::Saved);
1279        cx.notify();
1280    }
1281
1282    /// This method is called to signal that the buffer has been discarded.
1283    pub fn discarded(&self, cx: &mut Context<Self>) {
1284        cx.emit(BufferEvent::Discarded);
1285        cx.notify();
1286    }
1287
1288    /// Reloads the contents of the buffer from disk.
1289    pub fn reload(&mut self, cx: &Context<Self>) -> oneshot::Receiver<Option<Transaction>> {
1290        let (tx, rx) = futures::channel::oneshot::channel();
1291        let prev_version = self.text.version();
1292        self.reload_task = Some(cx.spawn(|this, mut cx| async move {
1293            let Some((new_mtime, new_text)) = this.update(&mut cx, |this, cx| {
1294                let file = this.file.as_ref()?.as_local()?;
1295                Some((file.disk_state().mtime(), file.load(cx)))
1296            })?
1297            else {
1298                return Ok(());
1299            };
1300
1301            let new_text = new_text.await?;
1302            let diff = this
1303                .update(&mut cx, |this, cx| this.diff(new_text.clone(), cx))?
1304                .await;
1305            this.update(&mut cx, |this, cx| {
1306                if this.version() == diff.base_version {
1307                    this.finalize_last_transaction();
1308                    this.apply_diff(diff, cx);
1309                    tx.send(this.finalize_last_transaction().cloned()).ok();
1310                    this.has_conflict = false;
1311                    this.did_reload(this.version(), this.line_ending(), new_mtime, cx);
1312                } else {
1313                    if !diff.edits.is_empty()
1314                        || this
1315                            .edits_since::<usize>(&diff.base_version)
1316                            .next()
1317                            .is_some()
1318                    {
1319                        this.has_conflict = true;
1320                    }
1321
1322                    this.did_reload(prev_version, this.line_ending(), this.saved_mtime, cx);
1323                }
1324
1325                this.reload_task.take();
1326            })
1327        }));
1328        rx
1329    }
1330
1331    /// This method is called to signal that the buffer has been reloaded.
1332    pub fn did_reload(
1333        &mut self,
1334        version: clock::Global,
1335        line_ending: LineEnding,
1336        mtime: Option<MTime>,
1337        cx: &mut Context<Self>,
1338    ) {
1339        self.saved_version = version;
1340        self.has_unsaved_edits
1341            .set((self.saved_version.clone(), false));
1342        self.text.set_line_ending(line_ending);
1343        self.saved_mtime = mtime;
1344        cx.emit(BufferEvent::Reloaded);
1345        cx.notify();
1346    }
1347
1348    /// Updates the [`File`] backing this buffer. This should be called when
1349    /// the file has changed or has been deleted.
1350    pub fn file_updated(&mut self, new_file: Arc<dyn File>, cx: &mut Context<Self>) {
1351        let was_dirty = self.is_dirty();
1352        let mut file_changed = false;
1353
1354        if let Some(old_file) = self.file.as_ref() {
1355            if new_file.path() != old_file.path() {
1356                file_changed = true;
1357            }
1358
1359            let old_state = old_file.disk_state();
1360            let new_state = new_file.disk_state();
1361            if old_state != new_state {
1362                file_changed = true;
1363                if !was_dirty && matches!(new_state, DiskState::Present { .. }) {
1364                    cx.emit(BufferEvent::ReloadNeeded)
1365                }
1366            }
1367        } else {
1368            file_changed = true;
1369        };
1370
1371        self.file = Some(new_file);
1372        if file_changed {
1373            self.non_text_state_update_count += 1;
1374            if was_dirty != self.is_dirty() {
1375                cx.emit(BufferEvent::DirtyChanged);
1376            }
1377            cx.emit(BufferEvent::FileHandleChanged);
1378            cx.notify();
1379        }
1380    }
1381
1382    pub fn base_buffer(&self) -> Option<Entity<Self>> {
1383        Some(self.branch_state.as_ref()?.base_buffer.clone())
1384    }
1385
1386    /// Returns the primary [`Language`] assigned to this [`Buffer`].
1387    pub fn language(&self) -> Option<&Arc<Language>> {
1388        self.language.as_ref()
1389    }
1390
1391    /// Returns the [`Language`] at the given location.
1392    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<Arc<Language>> {
1393        let offset = position.to_offset(self);
1394        self.syntax_map
1395            .lock()
1396            .layers_for_range(offset..offset, &self.text, false)
1397            .last()
1398            .map(|info| info.language.clone())
1399            .or_else(|| self.language.clone())
1400    }
1401
1402    /// An integer version number that accounts for all updates besides
1403    /// the buffer's text itself (which is versioned via a version vector).
1404    pub fn non_text_state_update_count(&self) -> usize {
1405        self.non_text_state_update_count
1406    }
1407
1408    /// Whether the buffer is being parsed in the background.
1409    #[cfg(any(test, feature = "test-support"))]
1410    pub fn is_parsing(&self) -> bool {
1411        self.parsing_in_background
1412    }
1413
1414    /// Indicates whether the buffer contains any regions that may be
1415    /// written in a language that hasn't been loaded yet.
1416    pub fn contains_unknown_injections(&self) -> bool {
1417        self.syntax_map.lock().contains_unknown_injections()
1418    }
1419
1420    #[cfg(test)]
1421    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
1422        self.sync_parse_timeout = timeout;
1423    }
1424
1425    /// Called after an edit to synchronize the buffer's main parse tree with
1426    /// the buffer's new underlying state.
1427    ///
1428    /// Locks the syntax map and interpolates the edits since the last reparse
1429    /// into the foreground syntax tree.
1430    ///
1431    /// Then takes a stable snapshot of the syntax map before unlocking it.
1432    /// The snapshot with the interpolated edits is sent to a background thread,
1433    /// where we ask Tree-sitter to perform an incremental parse.
1434    ///
1435    /// Meanwhile, in the foreground, we block the main thread for up to 1ms
1436    /// waiting on the parse to complete. As soon as it completes, we proceed
1437    /// synchronously, unless a 1ms timeout elapses.
1438    ///
1439    /// If we time out waiting on the parse, we spawn a second task waiting
1440    /// until the parse does complete and return with the interpolated tree still
1441    /// in the foreground. When the background parse completes, call back into
1442    /// the main thread and assign the foreground parse state.
1443    ///
1444    /// If the buffer or grammar changed since the start of the background parse,
1445    /// initiate an additional reparse recursively. To avoid concurrent parses
1446    /// for the same buffer, we only initiate a new parse if we are not already
1447    /// parsing in the background.
1448    pub fn reparse(&mut self, cx: &mut Context<Self>) {
1449        if self.parsing_in_background {
1450            return;
1451        }
1452        let language = if let Some(language) = self.language.clone() {
1453            language
1454        } else {
1455            return;
1456        };
1457
1458        let text = self.text_snapshot();
1459        let parsed_version = self.version();
1460
1461        let mut syntax_map = self.syntax_map.lock();
1462        syntax_map.interpolate(&text);
1463        let language_registry = syntax_map.language_registry();
1464        let mut syntax_snapshot = syntax_map.snapshot();
1465        drop(syntax_map);
1466
1467        let parse_task = cx.background_executor().spawn({
1468            let language = language.clone();
1469            let language_registry = language_registry.clone();
1470            async move {
1471                syntax_snapshot.reparse(&text, language_registry, language);
1472                syntax_snapshot
1473            }
1474        });
1475
1476        self.parse_status.0.send(ParseStatus::Parsing).unwrap();
1477        match cx
1478            .background_executor()
1479            .block_with_timeout(self.sync_parse_timeout, parse_task)
1480        {
1481            Ok(new_syntax_snapshot) => {
1482                self.did_finish_parsing(new_syntax_snapshot, cx);
1483            }
1484            Err(parse_task) => {
1485                self.parsing_in_background = true;
1486                cx.spawn(move |this, mut cx| async move {
1487                    let new_syntax_map = parse_task.await;
1488                    this.update(&mut cx, move |this, cx| {
1489                        let grammar_changed =
1490                            this.language.as_ref().map_or(true, |current_language| {
1491                                !Arc::ptr_eq(&language, current_language)
1492                            });
1493                        let language_registry_changed = new_syntax_map
1494                            .contains_unknown_injections()
1495                            && language_registry.map_or(false, |registry| {
1496                                registry.version() != new_syntax_map.language_registry_version()
1497                            });
1498                        let parse_again = language_registry_changed
1499                            || grammar_changed
1500                            || this.version.changed_since(&parsed_version);
1501                        this.did_finish_parsing(new_syntax_map, cx);
1502                        this.parsing_in_background = false;
1503                        if parse_again {
1504                            this.reparse(cx);
1505                        }
1506                    })
1507                    .ok();
1508                })
1509                .detach();
1510            }
1511        }
1512    }
1513
1514    fn did_finish_parsing(&mut self, syntax_snapshot: SyntaxSnapshot, cx: &mut Context<Self>) {
1515        self.non_text_state_update_count += 1;
1516        self.syntax_map.lock().did_parse(syntax_snapshot);
1517        self.request_autoindent(cx);
1518        self.parse_status.0.send(ParseStatus::Idle).unwrap();
1519        cx.emit(BufferEvent::Reparsed);
1520        cx.notify();
1521    }
1522
1523    pub fn parse_status(&self) -> watch::Receiver<ParseStatus> {
1524        self.parse_status.1.clone()
1525    }
1526
1527    /// Assign to the buffer a set of diagnostics created by a given language server.
1528    pub fn update_diagnostics(
1529        &mut self,
1530        server_id: LanguageServerId,
1531        diagnostics: DiagnosticSet,
1532        cx: &mut Context<Self>,
1533    ) {
1534        let lamport_timestamp = self.text.lamport_clock.tick();
1535        let op = Operation::UpdateDiagnostics {
1536            server_id,
1537            diagnostics: diagnostics.iter().cloned().collect(),
1538            lamport_timestamp,
1539        };
1540        self.apply_diagnostic_update(server_id, diagnostics, lamport_timestamp, cx);
1541        self.send_operation(op, true, cx);
1542    }
1543
1544    fn request_autoindent(&mut self, cx: &mut Context<Self>) {
1545        if let Some(indent_sizes) = self.compute_autoindents() {
1546            let indent_sizes = cx.background_executor().spawn(indent_sizes);
1547            match cx
1548                .background_executor()
1549                .block_with_timeout(Duration::from_micros(500), indent_sizes)
1550            {
1551                Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
1552                Err(indent_sizes) => {
1553                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
1554                        let indent_sizes = indent_sizes.await;
1555                        this.update(&mut cx, |this, cx| {
1556                            this.apply_autoindents(indent_sizes, cx);
1557                        })
1558                        .ok();
1559                    }));
1560                }
1561            }
1562        } else {
1563            self.autoindent_requests.clear();
1564        }
1565    }
1566
1567    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>>> {
1568        let max_rows_between_yields = 100;
1569        let snapshot = self.snapshot();
1570        if snapshot.syntax.is_empty() || self.autoindent_requests.is_empty() {
1571            return None;
1572        }
1573
1574        let autoindent_requests = self.autoindent_requests.clone();
1575        Some(async move {
1576            let mut indent_sizes = BTreeMap::<u32, (IndentSize, bool)>::new();
1577            for request in autoindent_requests {
1578                // Resolve each edited range to its row in the current buffer and in the
1579                // buffer before this batch of edits.
1580                let mut row_ranges = Vec::new();
1581                let mut old_to_new_rows = BTreeMap::new();
1582                let mut language_indent_sizes_by_new_row = Vec::new();
1583                for entry in &request.entries {
1584                    let position = entry.range.start;
1585                    let new_row = position.to_point(&snapshot).row;
1586                    let new_end_row = entry.range.end.to_point(&snapshot).row + 1;
1587                    language_indent_sizes_by_new_row.push((new_row, entry.indent_size));
1588
1589                    if !entry.first_line_is_new {
1590                        let old_row = position.to_point(&request.before_edit).row;
1591                        old_to_new_rows.insert(old_row, new_row);
1592                    }
1593                    row_ranges.push((new_row..new_end_row, entry.original_indent_column));
1594                }
1595
1596                // Build a map containing the suggested indentation for each of the edited lines
1597                // with respect to the state of the buffer before these edits. This map is keyed
1598                // by the rows for these lines in the current state of the buffer.
1599                let mut old_suggestions = BTreeMap::<u32, (IndentSize, bool)>::default();
1600                let old_edited_ranges =
1601                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
1602                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1603                let mut language_indent_size = IndentSize::default();
1604                for old_edited_range in old_edited_ranges {
1605                    let suggestions = request
1606                        .before_edit
1607                        .suggest_autoindents(old_edited_range.clone())
1608                        .into_iter()
1609                        .flatten();
1610                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
1611                        if let Some(suggestion) = suggestion {
1612                            let new_row = *old_to_new_rows.get(&old_row).unwrap();
1613
1614                            // Find the indent size based on the language for this row.
1615                            while let Some((row, size)) = language_indent_sizes.peek() {
1616                                if *row > new_row {
1617                                    break;
1618                                }
1619                                language_indent_size = *size;
1620                                language_indent_sizes.next();
1621                            }
1622
1623                            let suggested_indent = old_to_new_rows
1624                                .get(&suggestion.basis_row)
1625                                .and_then(|from_row| {
1626                                    Some(old_suggestions.get(from_row).copied()?.0)
1627                                })
1628                                .unwrap_or_else(|| {
1629                                    request
1630                                        .before_edit
1631                                        .indent_size_for_line(suggestion.basis_row)
1632                                })
1633                                .with_delta(suggestion.delta, language_indent_size);
1634                            old_suggestions
1635                                .insert(new_row, (suggested_indent, suggestion.within_error));
1636                        }
1637                    }
1638                    yield_now().await;
1639                }
1640
1641                // Compute new suggestions for each line, but only include them in the result
1642                // if they differ from the old suggestion for that line.
1643                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1644                let mut language_indent_size = IndentSize::default();
1645                for (row_range, original_indent_column) in row_ranges {
1646                    let new_edited_row_range = if request.is_block_mode {
1647                        row_range.start..row_range.start + 1
1648                    } else {
1649                        row_range.clone()
1650                    };
1651
1652                    let suggestions = snapshot
1653                        .suggest_autoindents(new_edited_row_range.clone())
1654                        .into_iter()
1655                        .flatten();
1656                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
1657                        if let Some(suggestion) = suggestion {
1658                            // Find the indent size based on the language for this row.
1659                            while let Some((row, size)) = language_indent_sizes.peek() {
1660                                if *row > new_row {
1661                                    break;
1662                                }
1663                                language_indent_size = *size;
1664                                language_indent_sizes.next();
1665                            }
1666
1667                            let suggested_indent = indent_sizes
1668                                .get(&suggestion.basis_row)
1669                                .copied()
1670                                .map(|e| e.0)
1671                                .unwrap_or_else(|| {
1672                                    snapshot.indent_size_for_line(suggestion.basis_row)
1673                                })
1674                                .with_delta(suggestion.delta, language_indent_size);
1675
1676                            if old_suggestions.get(&new_row).map_or(
1677                                true,
1678                                |(old_indentation, was_within_error)| {
1679                                    suggested_indent != *old_indentation
1680                                        && (!suggestion.within_error || *was_within_error)
1681                                },
1682                            ) {
1683                                indent_sizes.insert(
1684                                    new_row,
1685                                    (suggested_indent, request.ignore_empty_lines),
1686                                );
1687                            }
1688                        }
1689                    }
1690
1691                    if let (true, Some(original_indent_column)) =
1692                        (request.is_block_mode, original_indent_column)
1693                    {
1694                        let new_indent =
1695                            if let Some((indent, _)) = indent_sizes.get(&row_range.start) {
1696                                *indent
1697                            } else {
1698                                snapshot.indent_size_for_line(row_range.start)
1699                            };
1700                        let delta = new_indent.len as i64 - original_indent_column as i64;
1701                        if delta != 0 {
1702                            for row in row_range.skip(1) {
1703                                indent_sizes.entry(row).or_insert_with(|| {
1704                                    let mut size = snapshot.indent_size_for_line(row);
1705                                    if size.kind == new_indent.kind {
1706                                        match delta.cmp(&0) {
1707                                            Ordering::Greater => size.len += delta as u32,
1708                                            Ordering::Less => {
1709                                                size.len = size.len.saturating_sub(-delta as u32)
1710                                            }
1711                                            Ordering::Equal => {}
1712                                        }
1713                                    }
1714                                    (size, request.ignore_empty_lines)
1715                                });
1716                            }
1717                        }
1718                    }
1719
1720                    yield_now().await;
1721                }
1722            }
1723
1724            indent_sizes
1725                .into_iter()
1726                .filter_map(|(row, (indent, ignore_empty_lines))| {
1727                    if ignore_empty_lines && snapshot.line_len(row) == 0 {
1728                        None
1729                    } else {
1730                        Some((row, indent))
1731                    }
1732                })
1733                .collect()
1734        })
1735    }
1736
1737    fn apply_autoindents(
1738        &mut self,
1739        indent_sizes: BTreeMap<u32, IndentSize>,
1740        cx: &mut Context<Self>,
1741    ) {
1742        self.autoindent_requests.clear();
1743
1744        let edits: Vec<_> = indent_sizes
1745            .into_iter()
1746            .filter_map(|(row, indent_size)| {
1747                let current_size = indent_size_for_line(self, row);
1748                Self::edit_for_indent_size_adjustment(row, current_size, indent_size)
1749            })
1750            .collect();
1751
1752        let preserve_preview = self.preserve_preview();
1753        self.edit(edits, None, cx);
1754        if preserve_preview {
1755            self.refresh_preview();
1756        }
1757    }
1758
1759    /// Create a minimal edit that will cause the given row to be indented
1760    /// with the given size. After applying this edit, the length of the line
1761    /// will always be at least `new_size.len`.
1762    pub fn edit_for_indent_size_adjustment(
1763        row: u32,
1764        current_size: IndentSize,
1765        new_size: IndentSize,
1766    ) -> Option<(Range<Point>, String)> {
1767        if new_size.kind == current_size.kind {
1768            match new_size.len.cmp(&current_size.len) {
1769                Ordering::Greater => {
1770                    let point = Point::new(row, 0);
1771                    Some((
1772                        point..point,
1773                        iter::repeat(new_size.char())
1774                            .take((new_size.len - current_size.len) as usize)
1775                            .collect::<String>(),
1776                    ))
1777                }
1778
1779                Ordering::Less => Some((
1780                    Point::new(row, 0)..Point::new(row, current_size.len - new_size.len),
1781                    String::new(),
1782                )),
1783
1784                Ordering::Equal => None,
1785            }
1786        } else {
1787            Some((
1788                Point::new(row, 0)..Point::new(row, current_size.len),
1789                iter::repeat(new_size.char())
1790                    .take(new_size.len as usize)
1791                    .collect::<String>(),
1792            ))
1793        }
1794    }
1795
1796    /// Spawns a background task that asynchronously computes a `Diff` between the buffer's text
1797    /// and the given new text.
1798    pub fn diff(&self, mut new_text: String, cx: &App) -> Task<Diff> {
1799        let old_text = self.as_rope().clone();
1800        let base_version = self.version();
1801        cx.background_executor()
1802            .spawn_labeled(*BUFFER_DIFF_TASK, async move {
1803                let old_text = old_text.to_string();
1804                let line_ending = LineEnding::detect(&new_text);
1805                LineEnding::normalize(&mut new_text);
1806
1807                let diff = TextDiff::from_chars(old_text.as_str(), new_text.as_str());
1808                let empty: Arc<str> = Arc::default();
1809
1810                let mut edits = Vec::new();
1811                let mut old_offset = 0;
1812                let mut new_offset = 0;
1813                let mut last_edit: Option<(Range<usize>, Range<usize>)> = None;
1814                for change in diff.iter_all_changes().map(Some).chain([None]) {
1815                    if let Some(change) = &change {
1816                        let len = change.value().len();
1817                        match change.tag() {
1818                            ChangeTag::Equal => {
1819                                old_offset += len;
1820                                new_offset += len;
1821                            }
1822                            ChangeTag::Delete => {
1823                                let old_end_offset = old_offset + len;
1824                                if let Some((last_old_range, _)) = &mut last_edit {
1825                                    last_old_range.end = old_end_offset;
1826                                } else {
1827                                    last_edit =
1828                                        Some((old_offset..old_end_offset, new_offset..new_offset));
1829                                }
1830                                old_offset = old_end_offset;
1831                            }
1832                            ChangeTag::Insert => {
1833                                let new_end_offset = new_offset + len;
1834                                if let Some((_, last_new_range)) = &mut last_edit {
1835                                    last_new_range.end = new_end_offset;
1836                                } else {
1837                                    last_edit =
1838                                        Some((old_offset..old_offset, new_offset..new_end_offset));
1839                                }
1840                                new_offset = new_end_offset;
1841                            }
1842                        }
1843                    }
1844
1845                    if let Some((old_range, new_range)) = &last_edit {
1846                        if old_offset > old_range.end
1847                            || new_offset > new_range.end
1848                            || change.is_none()
1849                        {
1850                            let text = if new_range.is_empty() {
1851                                empty.clone()
1852                            } else {
1853                                new_text[new_range.clone()].into()
1854                            };
1855                            edits.push((old_range.clone(), text));
1856                            last_edit.take();
1857                        }
1858                    }
1859                }
1860
1861                Diff {
1862                    base_version,
1863                    line_ending,
1864                    edits,
1865                }
1866            })
1867    }
1868
1869    /// Spawns a background task that searches the buffer for any whitespace
1870    /// at the ends of a lines, and returns a `Diff` that removes that whitespace.
1871    pub fn remove_trailing_whitespace(&self, cx: &App) -> Task<Diff> {
1872        let old_text = self.as_rope().clone();
1873        let line_ending = self.line_ending();
1874        let base_version = self.version();
1875        cx.background_executor().spawn(async move {
1876            let ranges = trailing_whitespace_ranges(&old_text);
1877            let empty = Arc::<str>::from("");
1878            Diff {
1879                base_version,
1880                line_ending,
1881                edits: ranges
1882                    .into_iter()
1883                    .map(|range| (range, empty.clone()))
1884                    .collect(),
1885            }
1886        })
1887    }
1888
1889    /// Ensures that the buffer ends with a single newline character, and
1890    /// no other whitespace.
1891    pub fn ensure_final_newline(&mut self, cx: &mut Context<Self>) {
1892        let len = self.len();
1893        let mut offset = len;
1894        for chunk in self.as_rope().reversed_chunks_in_range(0..len) {
1895            let non_whitespace_len = chunk
1896                .trim_end_matches(|c: char| c.is_ascii_whitespace())
1897                .len();
1898            offset -= chunk.len();
1899            offset += non_whitespace_len;
1900            if non_whitespace_len != 0 {
1901                if offset == len - 1 && chunk.get(non_whitespace_len..) == Some("\n") {
1902                    return;
1903                }
1904                break;
1905            }
1906        }
1907        self.edit([(offset..len, "\n")], None, cx);
1908    }
1909
1910    /// Applies a diff to the buffer. If the buffer has changed since the given diff was
1911    /// calculated, then adjust the diff to account for those changes, and discard any
1912    /// parts of the diff that conflict with those changes.
1913    pub fn apply_diff(&mut self, diff: Diff, cx: &mut Context<Self>) -> Option<TransactionId> {
1914        // Check for any edits to the buffer that have occurred since this diff
1915        // was computed.
1916        let snapshot = self.snapshot();
1917        let mut edits_since = snapshot.edits_since::<usize>(&diff.base_version).peekable();
1918        let mut delta = 0;
1919        let adjusted_edits = diff.edits.into_iter().filter_map(|(range, new_text)| {
1920            while let Some(edit_since) = edits_since.peek() {
1921                // If the edit occurs after a diff hunk, then it does not
1922                // affect that hunk.
1923                if edit_since.old.start > range.end {
1924                    break;
1925                }
1926                // If the edit precedes the diff hunk, then adjust the hunk
1927                // to reflect the edit.
1928                else if edit_since.old.end < range.start {
1929                    delta += edit_since.new_len() as i64 - edit_since.old_len() as i64;
1930                    edits_since.next();
1931                }
1932                // If the edit intersects a diff hunk, then discard that hunk.
1933                else {
1934                    return None;
1935                }
1936            }
1937
1938            let start = (range.start as i64 + delta) as usize;
1939            let end = (range.end as i64 + delta) as usize;
1940            Some((start..end, new_text))
1941        });
1942
1943        self.start_transaction();
1944        self.text.set_line_ending(diff.line_ending);
1945        self.edit(adjusted_edits, None, cx);
1946        self.end_transaction(cx)
1947    }
1948
1949    fn has_unsaved_edits(&self) -> bool {
1950        let (last_version, has_unsaved_edits) = self.has_unsaved_edits.take();
1951
1952        if last_version == self.version {
1953            self.has_unsaved_edits
1954                .set((last_version, has_unsaved_edits));
1955            return has_unsaved_edits;
1956        }
1957
1958        let has_edits = self.has_edits_since(&self.saved_version);
1959        self.has_unsaved_edits
1960            .set((self.version.clone(), has_edits));
1961        has_edits
1962    }
1963
1964    /// Checks if the buffer has unsaved changes.
1965    pub fn is_dirty(&self) -> bool {
1966        if self.capability == Capability::ReadOnly {
1967            return false;
1968        }
1969        if self.has_conflict || self.has_unsaved_edits() {
1970            return true;
1971        }
1972        match self.file.as_ref().map(|f| f.disk_state()) {
1973            Some(DiskState::New) => !self.is_empty(),
1974            Some(DiskState::Deleted) => true,
1975            _ => false,
1976        }
1977    }
1978
1979    /// Checks if the buffer and its file have both changed since the buffer
1980    /// was last saved or reloaded.
1981    pub fn has_conflict(&self) -> bool {
1982        if self.has_conflict {
1983            return true;
1984        }
1985        let Some(file) = self.file.as_ref() else {
1986            return false;
1987        };
1988        match file.disk_state() {
1989            DiskState::New => false,
1990            DiskState::Present { mtime } => match self.saved_mtime {
1991                Some(saved_mtime) => {
1992                    mtime.bad_is_greater_than(saved_mtime) && self.has_unsaved_edits()
1993                }
1994                None => true,
1995            },
1996            DiskState::Deleted => true,
1997        }
1998    }
1999
2000    /// Gets a [`Subscription`] that tracks all of the changes to the buffer's text.
2001    pub fn subscribe(&mut self) -> Subscription {
2002        self.text.subscribe()
2003    }
2004
2005    /// Starts a transaction, if one is not already in-progress. When undoing or
2006    /// redoing edits, all of the edits performed within a transaction are undone
2007    /// or redone together.
2008    pub fn start_transaction(&mut self) -> Option<TransactionId> {
2009        self.start_transaction_at(Instant::now())
2010    }
2011
2012    /// Starts a transaction, providing the current time. Subsequent transactions
2013    /// that occur within a short period of time will be grouped together. This
2014    /// is controlled by the buffer's undo grouping duration.
2015    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
2016        self.transaction_depth += 1;
2017        if self.was_dirty_before_starting_transaction.is_none() {
2018            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
2019        }
2020        self.text.start_transaction_at(now)
2021    }
2022
2023    /// Terminates the current transaction, if this is the outermost transaction.
2024    pub fn end_transaction(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2025        self.end_transaction_at(Instant::now(), cx)
2026    }
2027
2028    /// Terminates the current transaction, providing the current time. Subsequent transactions
2029    /// that occur within a short period of time will be grouped together. This
2030    /// is controlled by the buffer's undo grouping duration.
2031    pub fn end_transaction_at(
2032        &mut self,
2033        now: Instant,
2034        cx: &mut Context<Self>,
2035    ) -> Option<TransactionId> {
2036        assert!(self.transaction_depth > 0);
2037        self.transaction_depth -= 1;
2038        let was_dirty = if self.transaction_depth == 0 {
2039            self.was_dirty_before_starting_transaction.take().unwrap()
2040        } else {
2041            false
2042        };
2043        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
2044            self.did_edit(&start_version, was_dirty, cx);
2045            Some(transaction_id)
2046        } else {
2047            None
2048        }
2049    }
2050
2051    /// Manually add a transaction to the buffer's undo history.
2052    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
2053        self.text.push_transaction(transaction, now);
2054    }
2055
2056    /// Prevent the last transaction from being grouped with any subsequent transactions,
2057    /// even if they occur with the buffer's undo grouping duration.
2058    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
2059        self.text.finalize_last_transaction()
2060    }
2061
2062    /// Manually group all changes since a given transaction.
2063    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
2064        self.text.group_until_transaction(transaction_id);
2065    }
2066
2067    /// Manually remove a transaction from the buffer's undo history
2068    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
2069        self.text.forget_transaction(transaction_id);
2070    }
2071
2072    /// Manually merge two adjacent transactions in the buffer's undo history.
2073    pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
2074        self.text.merge_transactions(transaction, destination);
2075    }
2076
2077    /// Waits for the buffer to receive operations with the given timestamps.
2078    pub fn wait_for_edits(
2079        &mut self,
2080        edit_ids: impl IntoIterator<Item = clock::Lamport>,
2081    ) -> impl Future<Output = Result<()>> {
2082        self.text.wait_for_edits(edit_ids)
2083    }
2084
2085    /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
2086    pub fn wait_for_anchors(
2087        &mut self,
2088        anchors: impl IntoIterator<Item = Anchor>,
2089    ) -> impl 'static + Future<Output = Result<()>> {
2090        self.text.wait_for_anchors(anchors)
2091    }
2092
2093    /// Waits for the buffer to receive operations up to the given version.
2094    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
2095        self.text.wait_for_version(version)
2096    }
2097
2098    /// Forces all futures returned by [`Buffer::wait_for_version`], [`Buffer::wait_for_edits`], or
2099    /// [`Buffer::wait_for_version`] to resolve with an error.
2100    pub fn give_up_waiting(&mut self) {
2101        self.text.give_up_waiting();
2102    }
2103
2104    /// Stores a set of selections that should be broadcasted to all of the buffer's replicas.
2105    pub fn set_active_selections(
2106        &mut self,
2107        selections: Arc<[Selection<Anchor>]>,
2108        line_mode: bool,
2109        cursor_shape: CursorShape,
2110        cx: &mut Context<Self>,
2111    ) {
2112        let lamport_timestamp = self.text.lamport_clock.tick();
2113        self.remote_selections.insert(
2114            self.text.replica_id(),
2115            SelectionSet {
2116                selections: selections.clone(),
2117                lamport_timestamp,
2118                line_mode,
2119                cursor_shape,
2120            },
2121        );
2122        self.send_operation(
2123            Operation::UpdateSelections {
2124                selections,
2125                line_mode,
2126                lamport_timestamp,
2127                cursor_shape,
2128            },
2129            true,
2130            cx,
2131        );
2132        self.non_text_state_update_count += 1;
2133        cx.notify();
2134    }
2135
2136    /// Clears the selections, so that other replicas of the buffer do not see any selections for
2137    /// this replica.
2138    pub fn remove_active_selections(&mut self, cx: &mut Context<Self>) {
2139        if self
2140            .remote_selections
2141            .get(&self.text.replica_id())
2142            .map_or(true, |set| !set.selections.is_empty())
2143        {
2144            self.set_active_selections(Arc::default(), false, Default::default(), cx);
2145        }
2146    }
2147
2148    /// Replaces the buffer's entire text.
2149    pub fn set_text<T>(&mut self, text: T, cx: &mut Context<Self>) -> Option<clock::Lamport>
2150    where
2151        T: Into<Arc<str>>,
2152    {
2153        self.autoindent_requests.clear();
2154        self.edit([(0..self.len(), text)], None, cx)
2155    }
2156
2157    /// Applies the given edits to the buffer. Each edit is specified as a range of text to
2158    /// delete, and a string of text to insert at that location.
2159    ///
2160    /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
2161    /// request for the edited ranges, which will be processed when the buffer finishes
2162    /// parsing.
2163    ///
2164    /// Parsing takes place at the end of a transaction, and may compute synchronously
2165    /// or asynchronously, depending on the changes.
2166    pub fn edit<I, S, T>(
2167        &mut self,
2168        edits_iter: I,
2169        autoindent_mode: Option<AutoindentMode>,
2170        cx: &mut Context<Self>,
2171    ) -> Option<clock::Lamport>
2172    where
2173        I: IntoIterator<Item = (Range<S>, T)>,
2174        S: ToOffset,
2175        T: Into<Arc<str>>,
2176    {
2177        // Skip invalid edits and coalesce contiguous ones.
2178        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
2179        for (range, new_text) in edits_iter {
2180            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2181            if range.start > range.end {
2182                mem::swap(&mut range.start, &mut range.end);
2183            }
2184            let new_text = new_text.into();
2185            if !new_text.is_empty() || !range.is_empty() {
2186                if let Some((prev_range, prev_text)) = edits.last_mut() {
2187                    if prev_range.end >= range.start {
2188                        prev_range.end = cmp::max(prev_range.end, range.end);
2189                        *prev_text = format!("{prev_text}{new_text}").into();
2190                    } else {
2191                        edits.push((range, new_text));
2192                    }
2193                } else {
2194                    edits.push((range, new_text));
2195                }
2196            }
2197        }
2198        if edits.is_empty() {
2199            return None;
2200        }
2201
2202        self.start_transaction();
2203        self.pending_autoindent.take();
2204        let autoindent_request = autoindent_mode
2205            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
2206
2207        let edit_operation = self.text.edit(edits.iter().cloned());
2208        let edit_id = edit_operation.timestamp();
2209
2210        if let Some((before_edit, mode)) = autoindent_request {
2211            let mut delta = 0isize;
2212            let entries = edits
2213                .into_iter()
2214                .enumerate()
2215                .zip(&edit_operation.as_edit().unwrap().new_text)
2216                .map(|((ix, (range, _)), new_text)| {
2217                    let new_text_length = new_text.len();
2218                    let old_start = range.start.to_point(&before_edit);
2219                    let new_start = (delta + range.start as isize) as usize;
2220                    let range_len = range.end - range.start;
2221                    delta += new_text_length as isize - range_len as isize;
2222
2223                    // Decide what range of the insertion to auto-indent, and whether
2224                    // the first line of the insertion should be considered a newly-inserted line
2225                    // or an edit to an existing line.
2226                    let mut range_of_insertion_to_indent = 0..new_text_length;
2227                    let mut first_line_is_new = true;
2228
2229                    let old_line_start = before_edit.indent_size_for_line(old_start.row).len;
2230                    let old_line_end = before_edit.line_len(old_start.row);
2231
2232                    if old_start.column > old_line_start {
2233                        first_line_is_new = false;
2234                    }
2235
2236                    if !new_text.contains('\n')
2237                        && (old_start.column + (range_len as u32) < old_line_end
2238                            || old_line_end == old_line_start)
2239                    {
2240                        first_line_is_new = false;
2241                    }
2242
2243                    // When inserting text starting with a newline, avoid auto-indenting the
2244                    // previous line.
2245                    if new_text.starts_with('\n') {
2246                        range_of_insertion_to_indent.start += 1;
2247                        first_line_is_new = true;
2248                    }
2249
2250                    let mut original_indent_column = None;
2251                    if let AutoindentMode::Block {
2252                        original_indent_columns,
2253                    } = &mode
2254                    {
2255                        original_indent_column =
2256                            Some(original_indent_columns.get(ix).copied().unwrap_or_else(|| {
2257                                indent_size_for_text(
2258                                    new_text[range_of_insertion_to_indent.clone()].chars(),
2259                                )
2260                                .len
2261                            }));
2262
2263                        // Avoid auto-indenting the line after the edit.
2264                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
2265                            range_of_insertion_to_indent.end -= 1;
2266                        }
2267                    }
2268
2269                    AutoindentRequestEntry {
2270                        first_line_is_new,
2271                        original_indent_column,
2272                        indent_size: before_edit.language_indent_size_at(range.start, cx),
2273                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
2274                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
2275                    }
2276                })
2277                .collect();
2278
2279            self.autoindent_requests.push(Arc::new(AutoindentRequest {
2280                before_edit,
2281                entries,
2282                is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
2283                ignore_empty_lines: false,
2284            }));
2285        }
2286
2287        self.end_transaction(cx);
2288        self.send_operation(Operation::Buffer(edit_operation), true, cx);
2289        Some(edit_id)
2290    }
2291
2292    fn did_edit(&mut self, old_version: &clock::Global, was_dirty: bool, cx: &mut Context<Self>) {
2293        if self.edits_since::<usize>(old_version).next().is_none() {
2294            return;
2295        }
2296
2297        self.reparse(cx);
2298
2299        cx.emit(BufferEvent::Edited);
2300        if was_dirty != self.is_dirty() {
2301            cx.emit(BufferEvent::DirtyChanged);
2302        }
2303        cx.notify();
2304    }
2305
2306    pub fn autoindent_ranges<I, T>(&mut self, ranges: I, cx: &mut Context<Self>)
2307    where
2308        I: IntoIterator<Item = Range<T>>,
2309        T: ToOffset + Copy,
2310    {
2311        let before_edit = self.snapshot();
2312        let entries = ranges
2313            .into_iter()
2314            .map(|range| AutoindentRequestEntry {
2315                range: before_edit.anchor_before(range.start)..before_edit.anchor_after(range.end),
2316                first_line_is_new: true,
2317                indent_size: before_edit.language_indent_size_at(range.start, cx),
2318                original_indent_column: None,
2319            })
2320            .collect();
2321        self.autoindent_requests.push(Arc::new(AutoindentRequest {
2322            before_edit,
2323            entries,
2324            is_block_mode: false,
2325            ignore_empty_lines: true,
2326        }));
2327        self.request_autoindent(cx);
2328    }
2329
2330    // Inserts newlines at the given position to create an empty line, returning the start of the new line.
2331    // You can also request the insertion of empty lines above and below the line starting at the returned point.
2332    pub fn insert_empty_line(
2333        &mut self,
2334        position: impl ToPoint,
2335        space_above: bool,
2336        space_below: bool,
2337        cx: &mut Context<Self>,
2338    ) -> Point {
2339        let mut position = position.to_point(self);
2340
2341        self.start_transaction();
2342
2343        self.edit(
2344            [(position..position, "\n")],
2345            Some(AutoindentMode::EachLine),
2346            cx,
2347        );
2348
2349        if position.column > 0 {
2350            position += Point::new(1, 0);
2351        }
2352
2353        if !self.is_line_blank(position.row) {
2354            self.edit(
2355                [(position..position, "\n")],
2356                Some(AutoindentMode::EachLine),
2357                cx,
2358            );
2359        }
2360
2361        if space_above && position.row > 0 && !self.is_line_blank(position.row - 1) {
2362            self.edit(
2363                [(position..position, "\n")],
2364                Some(AutoindentMode::EachLine),
2365                cx,
2366            );
2367            position.row += 1;
2368        }
2369
2370        if space_below
2371            && (position.row == self.max_point().row || !self.is_line_blank(position.row + 1))
2372        {
2373            self.edit(
2374                [(position..position, "\n")],
2375                Some(AutoindentMode::EachLine),
2376                cx,
2377            );
2378        }
2379
2380        self.end_transaction(cx);
2381
2382        position
2383    }
2384
2385    /// Applies the given remote operations to the buffer.
2386    pub fn apply_ops<I: IntoIterator<Item = Operation>>(&mut self, ops: I, cx: &mut Context<Self>) {
2387        self.pending_autoindent.take();
2388        let was_dirty = self.is_dirty();
2389        let old_version = self.version.clone();
2390        let mut deferred_ops = Vec::new();
2391        let buffer_ops = ops
2392            .into_iter()
2393            .filter_map(|op| match op {
2394                Operation::Buffer(op) => Some(op),
2395                _ => {
2396                    if self.can_apply_op(&op) {
2397                        self.apply_op(op, cx);
2398                    } else {
2399                        deferred_ops.push(op);
2400                    }
2401                    None
2402                }
2403            })
2404            .collect::<Vec<_>>();
2405        for operation in buffer_ops.iter() {
2406            self.send_operation(Operation::Buffer(operation.clone()), false, cx);
2407        }
2408        self.text.apply_ops(buffer_ops);
2409        self.deferred_ops.insert(deferred_ops);
2410        self.flush_deferred_ops(cx);
2411        self.did_edit(&old_version, was_dirty, cx);
2412        // Notify independently of whether the buffer was edited as the operations could include a
2413        // selection update.
2414        cx.notify();
2415    }
2416
2417    fn flush_deferred_ops(&mut self, cx: &mut Context<Self>) {
2418        let mut deferred_ops = Vec::new();
2419        for op in self.deferred_ops.drain().iter().cloned() {
2420            if self.can_apply_op(&op) {
2421                self.apply_op(op, cx);
2422            } else {
2423                deferred_ops.push(op);
2424            }
2425        }
2426        self.deferred_ops.insert(deferred_ops);
2427    }
2428
2429    pub fn has_deferred_ops(&self) -> bool {
2430        !self.deferred_ops.is_empty() || self.text.has_deferred_ops()
2431    }
2432
2433    fn can_apply_op(&self, operation: &Operation) -> bool {
2434        match operation {
2435            Operation::Buffer(_) => {
2436                unreachable!("buffer operations should never be applied at this layer")
2437            }
2438            Operation::UpdateDiagnostics {
2439                diagnostics: diagnostic_set,
2440                ..
2441            } => diagnostic_set.iter().all(|diagnostic| {
2442                self.text.can_resolve(&diagnostic.range.start)
2443                    && self.text.can_resolve(&diagnostic.range.end)
2444            }),
2445            Operation::UpdateSelections { selections, .. } => selections
2446                .iter()
2447                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
2448            Operation::UpdateCompletionTriggers { .. } => true,
2449        }
2450    }
2451
2452    fn apply_op(&mut self, operation: Operation, cx: &mut Context<Self>) {
2453        match operation {
2454            Operation::Buffer(_) => {
2455                unreachable!("buffer operations should never be applied at this layer")
2456            }
2457            Operation::UpdateDiagnostics {
2458                server_id,
2459                diagnostics: diagnostic_set,
2460                lamport_timestamp,
2461            } => {
2462                let snapshot = self.snapshot();
2463                self.apply_diagnostic_update(
2464                    server_id,
2465                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
2466                    lamport_timestamp,
2467                    cx,
2468                );
2469            }
2470            Operation::UpdateSelections {
2471                selections,
2472                lamport_timestamp,
2473                line_mode,
2474                cursor_shape,
2475            } => {
2476                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
2477                    if set.lamport_timestamp > lamport_timestamp {
2478                        return;
2479                    }
2480                }
2481
2482                self.remote_selections.insert(
2483                    lamport_timestamp.replica_id,
2484                    SelectionSet {
2485                        selections,
2486                        lamport_timestamp,
2487                        line_mode,
2488                        cursor_shape,
2489                    },
2490                );
2491                self.text.lamport_clock.observe(lamport_timestamp);
2492                self.non_text_state_update_count += 1;
2493            }
2494            Operation::UpdateCompletionTriggers {
2495                triggers,
2496                lamport_timestamp,
2497                server_id,
2498            } => {
2499                if triggers.is_empty() {
2500                    self.completion_triggers_per_language_server
2501                        .remove(&server_id);
2502                    self.completion_triggers = self
2503                        .completion_triggers_per_language_server
2504                        .values()
2505                        .flat_map(|triggers| triggers.into_iter().cloned())
2506                        .collect();
2507                } else {
2508                    self.completion_triggers_per_language_server
2509                        .insert(server_id, triggers.iter().cloned().collect());
2510                    self.completion_triggers.extend(triggers);
2511                }
2512                self.text.lamport_clock.observe(lamport_timestamp);
2513            }
2514        }
2515    }
2516
2517    fn apply_diagnostic_update(
2518        &mut self,
2519        server_id: LanguageServerId,
2520        diagnostics: DiagnosticSet,
2521        lamport_timestamp: clock::Lamport,
2522        cx: &mut Context<Self>,
2523    ) {
2524        if lamport_timestamp > self.diagnostics_timestamp {
2525            let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
2526            if diagnostics.is_empty() {
2527                if let Ok(ix) = ix {
2528                    self.diagnostics.remove(ix);
2529                }
2530            } else {
2531                match ix {
2532                    Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
2533                    Ok(ix) => self.diagnostics[ix].1 = diagnostics,
2534                };
2535            }
2536            self.diagnostics_timestamp = lamport_timestamp;
2537            self.non_text_state_update_count += 1;
2538            self.text.lamport_clock.observe(lamport_timestamp);
2539            cx.notify();
2540            cx.emit(BufferEvent::DiagnosticsUpdated);
2541        }
2542    }
2543
2544    fn send_operation(&self, operation: Operation, is_local: bool, cx: &mut Context<Self>) {
2545        cx.emit(BufferEvent::Operation {
2546            operation,
2547            is_local,
2548        });
2549    }
2550
2551    /// Removes the selections for a given peer.
2552    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut Context<Self>) {
2553        self.remote_selections.remove(&replica_id);
2554        cx.notify();
2555    }
2556
2557    /// Undoes the most recent transaction.
2558    pub fn undo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2559        let was_dirty = self.is_dirty();
2560        let old_version = self.version.clone();
2561
2562        if let Some((transaction_id, operation)) = self.text.undo() {
2563            self.send_operation(Operation::Buffer(operation), true, cx);
2564            self.did_edit(&old_version, was_dirty, cx);
2565            Some(transaction_id)
2566        } else {
2567            None
2568        }
2569    }
2570
2571    /// Manually undoes a specific transaction in the buffer's undo history.
2572    pub fn undo_transaction(
2573        &mut self,
2574        transaction_id: TransactionId,
2575        cx: &mut Context<Self>,
2576    ) -> bool {
2577        let was_dirty = self.is_dirty();
2578        let old_version = self.version.clone();
2579        if let Some(operation) = self.text.undo_transaction(transaction_id) {
2580            self.send_operation(Operation::Buffer(operation), true, cx);
2581            self.did_edit(&old_version, was_dirty, cx);
2582            true
2583        } else {
2584            false
2585        }
2586    }
2587
2588    /// Manually undoes all changes after a given transaction in the buffer's undo history.
2589    pub fn undo_to_transaction(
2590        &mut self,
2591        transaction_id: TransactionId,
2592        cx: &mut Context<Self>,
2593    ) -> bool {
2594        let was_dirty = self.is_dirty();
2595        let old_version = self.version.clone();
2596
2597        let operations = self.text.undo_to_transaction(transaction_id);
2598        let undone = !operations.is_empty();
2599        for operation in operations {
2600            self.send_operation(Operation::Buffer(operation), true, cx);
2601        }
2602        if undone {
2603            self.did_edit(&old_version, was_dirty, cx)
2604        }
2605        undone
2606    }
2607
2608    pub fn undo_operations(&mut self, counts: HashMap<Lamport, u32>, cx: &mut Context<Buffer>) {
2609        let was_dirty = self.is_dirty();
2610        let operation = self.text.undo_operations(counts);
2611        let old_version = self.version.clone();
2612        self.send_operation(Operation::Buffer(operation), true, cx);
2613        self.did_edit(&old_version, was_dirty, cx);
2614    }
2615
2616    /// Manually redoes a specific transaction in the buffer's redo history.
2617    pub fn redo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2618        let was_dirty = self.is_dirty();
2619        let old_version = self.version.clone();
2620
2621        if let Some((transaction_id, operation)) = self.text.redo() {
2622            self.send_operation(Operation::Buffer(operation), true, cx);
2623            self.did_edit(&old_version, was_dirty, cx);
2624            Some(transaction_id)
2625        } else {
2626            None
2627        }
2628    }
2629
2630    /// Manually undoes all changes until a given transaction in the buffer's redo history.
2631    pub fn redo_to_transaction(
2632        &mut self,
2633        transaction_id: TransactionId,
2634        cx: &mut Context<Self>,
2635    ) -> bool {
2636        let was_dirty = self.is_dirty();
2637        let old_version = self.version.clone();
2638
2639        let operations = self.text.redo_to_transaction(transaction_id);
2640        let redone = !operations.is_empty();
2641        for operation in operations {
2642            self.send_operation(Operation::Buffer(operation), true, cx);
2643        }
2644        if redone {
2645            self.did_edit(&old_version, was_dirty, cx)
2646        }
2647        redone
2648    }
2649
2650    /// Override current completion triggers with the user-provided completion triggers.
2651    pub fn set_completion_triggers(
2652        &mut self,
2653        server_id: LanguageServerId,
2654        triggers: BTreeSet<String>,
2655        cx: &mut Context<Self>,
2656    ) {
2657        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2658        if triggers.is_empty() {
2659            self.completion_triggers_per_language_server
2660                .remove(&server_id);
2661            self.completion_triggers = self
2662                .completion_triggers_per_language_server
2663                .values()
2664                .flat_map(|triggers| triggers.into_iter().cloned())
2665                .collect();
2666        } else {
2667            self.completion_triggers_per_language_server
2668                .insert(server_id, triggers.clone());
2669            self.completion_triggers.extend(triggers.iter().cloned());
2670        }
2671        self.send_operation(
2672            Operation::UpdateCompletionTriggers {
2673                triggers: triggers.iter().cloned().collect(),
2674                lamport_timestamp: self.completion_triggers_timestamp,
2675                server_id,
2676            },
2677            true,
2678            cx,
2679        );
2680        cx.notify();
2681    }
2682
2683    /// Returns a list of strings which trigger a completion menu for this language.
2684    /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2685    pub fn completion_triggers(&self) -> &BTreeSet<String> {
2686        &self.completion_triggers
2687    }
2688
2689    /// Call this directly after performing edits to prevent the preview tab
2690    /// from being dismissed by those edits. It causes `should_dismiss_preview`
2691    /// to return false until there are additional edits.
2692    pub fn refresh_preview(&mut self) {
2693        self.preview_version = self.version.clone();
2694    }
2695
2696    /// Whether we should preserve the preview status of a tab containing this buffer.
2697    pub fn preserve_preview(&self) -> bool {
2698        !self.has_edits_since(&self.preview_version)
2699    }
2700}
2701
2702#[doc(hidden)]
2703#[cfg(any(test, feature = "test-support"))]
2704impl Buffer {
2705    pub fn edit_via_marked_text(
2706        &mut self,
2707        marked_string: &str,
2708        autoindent_mode: Option<AutoindentMode>,
2709        cx: &mut Context<Self>,
2710    ) {
2711        let edits = self.edits_for_marked_text(marked_string);
2712        self.edit(edits, autoindent_mode, cx);
2713    }
2714
2715    pub fn set_group_interval(&mut self, group_interval: Duration) {
2716        self.text.set_group_interval(group_interval);
2717    }
2718
2719    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize, cx: &mut Context<Self>)
2720    where
2721        T: rand::Rng,
2722    {
2723        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2724        let mut last_end = None;
2725        for _ in 0..old_range_count {
2726            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2727                break;
2728            }
2729
2730            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2731            let mut range = self.random_byte_range(new_start, rng);
2732            if rng.gen_bool(0.2) {
2733                mem::swap(&mut range.start, &mut range.end);
2734            }
2735            last_end = Some(range.end);
2736
2737            let new_text_len = rng.gen_range(0..10);
2738            let mut new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2739            new_text = new_text.to_uppercase();
2740
2741            edits.push((range, new_text));
2742        }
2743        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2744        self.edit(edits, None, cx);
2745    }
2746
2747    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut Context<Self>) {
2748        let was_dirty = self.is_dirty();
2749        let old_version = self.version.clone();
2750
2751        let ops = self.text.randomly_undo_redo(rng);
2752        if !ops.is_empty() {
2753            for op in ops {
2754                self.send_operation(Operation::Buffer(op), true, cx);
2755                self.did_edit(&old_version, was_dirty, cx);
2756            }
2757        }
2758    }
2759}
2760
2761impl EventEmitter<BufferEvent> for Buffer {}
2762
2763impl Deref for Buffer {
2764    type Target = TextBuffer;
2765
2766    fn deref(&self) -> &Self::Target {
2767        &self.text
2768    }
2769}
2770
2771impl BufferSnapshot {
2772    /// Returns [`IndentSize`] for a given line that respects user settings and /// language preferences.
2773    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2774        indent_size_for_line(self, row)
2775    }
2776    /// Returns [`IndentSize`] for a given position that respects user settings
2777    /// and language preferences.
2778    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &App) -> IndentSize {
2779        let settings = language_settings(
2780            self.language_at(position).map(|l| l.name()),
2781            self.file(),
2782            cx,
2783        );
2784        if settings.hard_tabs {
2785            IndentSize::tab()
2786        } else {
2787            IndentSize::spaces(settings.tab_size.get())
2788        }
2789    }
2790
2791    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2792    /// is passed in as `single_indent_size`.
2793    pub fn suggested_indents(
2794        &self,
2795        rows: impl Iterator<Item = u32>,
2796        single_indent_size: IndentSize,
2797    ) -> BTreeMap<u32, IndentSize> {
2798        let mut result = BTreeMap::new();
2799
2800        for row_range in contiguous_ranges(rows, 10) {
2801            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2802                Some(suggestions) => suggestions,
2803                _ => break,
2804            };
2805
2806            for (row, suggestion) in row_range.zip(suggestions) {
2807                let indent_size = if let Some(suggestion) = suggestion {
2808                    result
2809                        .get(&suggestion.basis_row)
2810                        .copied()
2811                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2812                        .with_delta(suggestion.delta, single_indent_size)
2813                } else {
2814                    self.indent_size_for_line(row)
2815                };
2816
2817                result.insert(row, indent_size);
2818            }
2819        }
2820
2821        result
2822    }
2823
2824    fn suggest_autoindents(
2825        &self,
2826        row_range: Range<u32>,
2827    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2828        let config = &self.language.as_ref()?.config;
2829        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2830
2831        // Find the suggested indentation ranges based on the syntax tree.
2832        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2833        let end = Point::new(row_range.end, 0);
2834        let range = (start..end).to_offset(&self.text);
2835        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2836            Some(&grammar.indents_config.as_ref()?.query)
2837        });
2838        let indent_configs = matches
2839            .grammars()
2840            .iter()
2841            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2842            .collect::<Vec<_>>();
2843
2844        let mut indent_ranges = Vec::<Range<Point>>::new();
2845        let mut outdent_positions = Vec::<Point>::new();
2846        while let Some(mat) = matches.peek() {
2847            let mut start: Option<Point> = None;
2848            let mut end: Option<Point> = None;
2849
2850            let config = &indent_configs[mat.grammar_index];
2851            for capture in mat.captures {
2852                if capture.index == config.indent_capture_ix {
2853                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2854                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2855                } else if Some(capture.index) == config.start_capture_ix {
2856                    start = Some(Point::from_ts_point(capture.node.end_position()));
2857                } else if Some(capture.index) == config.end_capture_ix {
2858                    end = Some(Point::from_ts_point(capture.node.start_position()));
2859                } else if Some(capture.index) == config.outdent_capture_ix {
2860                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2861                }
2862            }
2863
2864            matches.advance();
2865            if let Some((start, end)) = start.zip(end) {
2866                if start.row == end.row {
2867                    continue;
2868                }
2869
2870                let range = start..end;
2871                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2872                    Err(ix) => indent_ranges.insert(ix, range),
2873                    Ok(ix) => {
2874                        let prev_range = &mut indent_ranges[ix];
2875                        prev_range.end = prev_range.end.max(range.end);
2876                    }
2877                }
2878            }
2879        }
2880
2881        let mut error_ranges = Vec::<Range<Point>>::new();
2882        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2883            Some(&grammar.error_query)
2884        });
2885        while let Some(mat) = matches.peek() {
2886            let node = mat.captures[0].node;
2887            let start = Point::from_ts_point(node.start_position());
2888            let end = Point::from_ts_point(node.end_position());
2889            let range = start..end;
2890            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2891                Ok(ix) | Err(ix) => ix,
2892            };
2893            let mut end_ix = ix;
2894            while let Some(existing_range) = error_ranges.get(end_ix) {
2895                if existing_range.end < end {
2896                    end_ix += 1;
2897                } else {
2898                    break;
2899                }
2900            }
2901            error_ranges.splice(ix..end_ix, [range]);
2902            matches.advance();
2903        }
2904
2905        outdent_positions.sort();
2906        for outdent_position in outdent_positions {
2907            // find the innermost indent range containing this outdent_position
2908            // set its end to the outdent position
2909            if let Some(range_to_truncate) = indent_ranges
2910                .iter_mut()
2911                .filter(|indent_range| indent_range.contains(&outdent_position))
2912                .last()
2913            {
2914                range_to_truncate.end = outdent_position;
2915            }
2916        }
2917
2918        // Find the suggested indentation increases and decreased based on regexes.
2919        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2920        self.for_each_line(
2921            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2922                ..Point::new(row_range.end, 0),
2923            |row, line| {
2924                if config
2925                    .decrease_indent_pattern
2926                    .as_ref()
2927                    .map_or(false, |regex| regex.is_match(line))
2928                {
2929                    indent_change_rows.push((row, Ordering::Less));
2930                }
2931                if config
2932                    .increase_indent_pattern
2933                    .as_ref()
2934                    .map_or(false, |regex| regex.is_match(line))
2935                {
2936                    indent_change_rows.push((row + 1, Ordering::Greater));
2937                }
2938            },
2939        );
2940
2941        let mut indent_changes = indent_change_rows.into_iter().peekable();
2942        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2943            prev_non_blank_row.unwrap_or(0)
2944        } else {
2945            row_range.start.saturating_sub(1)
2946        };
2947        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2948        Some(row_range.map(move |row| {
2949            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2950
2951            let mut indent_from_prev_row = false;
2952            let mut outdent_from_prev_row = false;
2953            let mut outdent_to_row = u32::MAX;
2954            let mut from_regex = false;
2955
2956            while let Some((indent_row, delta)) = indent_changes.peek() {
2957                match indent_row.cmp(&row) {
2958                    Ordering::Equal => match delta {
2959                        Ordering::Less => {
2960                            from_regex = true;
2961                            outdent_from_prev_row = true
2962                        }
2963                        Ordering::Greater => {
2964                            indent_from_prev_row = true;
2965                            from_regex = true
2966                        }
2967                        _ => {}
2968                    },
2969
2970                    Ordering::Greater => break,
2971                    Ordering::Less => {}
2972                }
2973
2974                indent_changes.next();
2975            }
2976
2977            for range in &indent_ranges {
2978                if range.start.row >= row {
2979                    break;
2980                }
2981                if range.start.row == prev_row && range.end > row_start {
2982                    indent_from_prev_row = true;
2983                }
2984                if range.end > prev_row_start && range.end <= row_start {
2985                    outdent_to_row = outdent_to_row.min(range.start.row);
2986                }
2987            }
2988
2989            let within_error = error_ranges
2990                .iter()
2991                .any(|e| e.start.row < row && e.end > row_start);
2992
2993            let suggestion = if outdent_to_row == prev_row
2994                || (outdent_from_prev_row && indent_from_prev_row)
2995            {
2996                Some(IndentSuggestion {
2997                    basis_row: prev_row,
2998                    delta: Ordering::Equal,
2999                    within_error: within_error && !from_regex,
3000                })
3001            } else if indent_from_prev_row {
3002                Some(IndentSuggestion {
3003                    basis_row: prev_row,
3004                    delta: Ordering::Greater,
3005                    within_error: within_error && !from_regex,
3006                })
3007            } else if outdent_to_row < prev_row {
3008                Some(IndentSuggestion {
3009                    basis_row: outdent_to_row,
3010                    delta: Ordering::Equal,
3011                    within_error: within_error && !from_regex,
3012                })
3013            } else if outdent_from_prev_row {
3014                Some(IndentSuggestion {
3015                    basis_row: prev_row,
3016                    delta: Ordering::Less,
3017                    within_error: within_error && !from_regex,
3018                })
3019            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
3020            {
3021                Some(IndentSuggestion {
3022                    basis_row: prev_row,
3023                    delta: Ordering::Equal,
3024                    within_error: within_error && !from_regex,
3025                })
3026            } else {
3027                None
3028            };
3029
3030            prev_row = row;
3031            prev_row_start = row_start;
3032            suggestion
3033        }))
3034    }
3035
3036    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
3037        while row > 0 {
3038            row -= 1;
3039            if !self.is_line_blank(row) {
3040                return Some(row);
3041            }
3042        }
3043        None
3044    }
3045
3046    fn get_highlights(&self, range: Range<usize>) -> (SyntaxMapCaptures, Vec<HighlightMap>) {
3047        let captures = self.syntax.captures(range, &self.text, |grammar| {
3048            grammar.highlights_query.as_ref()
3049        });
3050        let highlight_maps = captures
3051            .grammars()
3052            .iter()
3053            .map(|grammar| grammar.highlight_map())
3054            .collect();
3055        (captures, highlight_maps)
3056    }
3057
3058    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
3059    /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
3060    /// returned in chunks where each chunk has a single syntax highlighting style and
3061    /// diagnostic status.
3062    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
3063        let range = range.start.to_offset(self)..range.end.to_offset(self);
3064
3065        let mut syntax = None;
3066        if language_aware {
3067            syntax = Some(self.get_highlights(range.clone()));
3068        }
3069        // We want to look at diagnostic spans only when iterating over language-annotated chunks.
3070        let diagnostics = language_aware;
3071        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostics, Some(self))
3072    }
3073
3074    pub fn highlighted_text_for_range<T: ToOffset>(
3075        &self,
3076        range: Range<T>,
3077        override_style: Option<HighlightStyle>,
3078        syntax_theme: &SyntaxTheme,
3079    ) -> HighlightedText {
3080        HighlightedText::from_buffer_range(
3081            range,
3082            &self.text,
3083            &self.syntax,
3084            override_style,
3085            syntax_theme,
3086        )
3087    }
3088
3089    /// Invokes the given callback for each line of text in the given range of the buffer.
3090    /// Uses callback to avoid allocating a string for each line.
3091    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
3092        let mut line = String::new();
3093        let mut row = range.start.row;
3094        for chunk in self
3095            .as_rope()
3096            .chunks_in_range(range.to_offset(self))
3097            .chain(["\n"])
3098        {
3099            for (newline_ix, text) in chunk.split('\n').enumerate() {
3100                if newline_ix > 0 {
3101                    callback(row, &line);
3102                    row += 1;
3103                    line.clear();
3104                }
3105                line.push_str(text);
3106            }
3107        }
3108    }
3109
3110    /// Iterates over every [`SyntaxLayer`] in the buffer.
3111    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
3112        self.syntax
3113            .layers_for_range(0..self.len(), &self.text, true)
3114    }
3115
3116    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
3117        let offset = position.to_offset(self);
3118        self.syntax
3119            .layers_for_range(offset..offset, &self.text, false)
3120            .filter(|l| l.node().end_byte() > offset)
3121            .last()
3122    }
3123
3124    /// Returns the main [`Language`].
3125    pub fn language(&self) -> Option<&Arc<Language>> {
3126        self.language.as_ref()
3127    }
3128
3129    /// Returns the [`Language`] at the given location.
3130    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
3131        self.syntax_layer_at(position)
3132            .map(|info| info.language)
3133            .or(self.language.as_ref())
3134    }
3135
3136    /// Returns the settings for the language at the given location.
3137    pub fn settings_at<'a, D: ToOffset>(
3138        &'a self,
3139        position: D,
3140        cx: &'a App,
3141    ) -> Cow<'a, LanguageSettings> {
3142        language_settings(
3143            self.language_at(position).map(|l| l.name()),
3144            self.file.as_ref(),
3145            cx,
3146        )
3147    }
3148
3149    pub fn char_classifier_at<T: ToOffset>(&self, point: T) -> CharClassifier {
3150        CharClassifier::new(self.language_scope_at(point))
3151    }
3152
3153    /// Returns the [`LanguageScope`] at the given location.
3154    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
3155        let offset = position.to_offset(self);
3156        let mut scope = None;
3157        let mut smallest_range: Option<Range<usize>> = None;
3158
3159        // Use the layer that has the smallest node intersecting the given point.
3160        for layer in self
3161            .syntax
3162            .layers_for_range(offset..offset, &self.text, false)
3163        {
3164            let mut cursor = layer.node().walk();
3165
3166            let mut range = None;
3167            loop {
3168                let child_range = cursor.node().byte_range();
3169                if !child_range.to_inclusive().contains(&offset) {
3170                    break;
3171                }
3172
3173                range = Some(child_range);
3174                if cursor.goto_first_child_for_byte(offset).is_none() {
3175                    break;
3176                }
3177            }
3178
3179            if let Some(range) = range {
3180                if smallest_range
3181                    .as_ref()
3182                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
3183                {
3184                    smallest_range = Some(range);
3185                    scope = Some(LanguageScope {
3186                        language: layer.language.clone(),
3187                        override_id: layer.override_id(offset, &self.text),
3188                    });
3189                }
3190            }
3191        }
3192
3193        scope.or_else(|| {
3194            self.language.clone().map(|language| LanguageScope {
3195                language,
3196                override_id: None,
3197            })
3198        })
3199    }
3200
3201    /// Returns a tuple of the range and character kind of the word
3202    /// surrounding the given position.
3203    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
3204        let mut start = start.to_offset(self);
3205        let mut end = start;
3206        let mut next_chars = self.chars_at(start).peekable();
3207        let mut prev_chars = self.reversed_chars_at(start).peekable();
3208
3209        let classifier = self.char_classifier_at(start);
3210        let word_kind = cmp::max(
3211            prev_chars.peek().copied().map(|c| classifier.kind(c)),
3212            next_chars.peek().copied().map(|c| classifier.kind(c)),
3213        );
3214
3215        for ch in prev_chars {
3216            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3217                start -= ch.len_utf8();
3218            } else {
3219                break;
3220            }
3221        }
3222
3223        for ch in next_chars {
3224            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3225                end += ch.len_utf8();
3226            } else {
3227                break;
3228            }
3229        }
3230
3231        (start..end, word_kind)
3232    }
3233
3234    /// Returns the closest syntax node enclosing the given range.
3235    pub fn syntax_ancestor<'a, T: ToOffset>(
3236        &'a self,
3237        range: Range<T>,
3238    ) -> Option<tree_sitter::Node<'a>> {
3239        let range = range.start.to_offset(self)..range.end.to_offset(self);
3240        let mut result: Option<tree_sitter::Node<'a>> = None;
3241        'outer: for layer in self
3242            .syntax
3243            .layers_for_range(range.clone(), &self.text, true)
3244        {
3245            let mut cursor = layer.node().walk();
3246
3247            // Descend to the first leaf that touches the start of the range,
3248            // and if the range is non-empty, extends beyond the start.
3249            while cursor.goto_first_child_for_byte(range.start).is_some() {
3250                if !range.is_empty() && cursor.node().end_byte() == range.start {
3251                    cursor.goto_next_sibling();
3252                }
3253            }
3254
3255            // Ascend to the smallest ancestor that strictly contains the range.
3256            loop {
3257                let node_range = cursor.node().byte_range();
3258                if node_range.start <= range.start
3259                    && node_range.end >= range.end
3260                    && node_range.len() > range.len()
3261                {
3262                    break;
3263                }
3264                if !cursor.goto_parent() {
3265                    continue 'outer;
3266                }
3267            }
3268
3269            let left_node = cursor.node();
3270            let mut layer_result = left_node;
3271
3272            // For an empty range, try to find another node immediately to the right of the range.
3273            if left_node.end_byte() == range.start {
3274                let mut right_node = None;
3275                while !cursor.goto_next_sibling() {
3276                    if !cursor.goto_parent() {
3277                        break;
3278                    }
3279                }
3280
3281                while cursor.node().start_byte() == range.start {
3282                    right_node = Some(cursor.node());
3283                    if !cursor.goto_first_child() {
3284                        break;
3285                    }
3286                }
3287
3288                // If there is a candidate node on both sides of the (empty) range, then
3289                // decide between the two by favoring a named node over an anonymous token.
3290                // If both nodes are the same in that regard, favor the right one.
3291                if let Some(right_node) = right_node {
3292                    if right_node.is_named() || !left_node.is_named() {
3293                        layer_result = right_node;
3294                    }
3295                }
3296            }
3297
3298            if let Some(previous_result) = &result {
3299                if previous_result.byte_range().len() < layer_result.byte_range().len() {
3300                    continue;
3301                }
3302            }
3303            result = Some(layer_result);
3304        }
3305
3306        result
3307    }
3308
3309    /// Returns the outline for the buffer.
3310    ///
3311    /// This method allows passing an optional [`SyntaxTheme`] to
3312    /// syntax-highlight the returned symbols.
3313    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3314        self.outline_items_containing(0..self.len(), true, theme)
3315            .map(Outline::new)
3316    }
3317
3318    /// Returns all the symbols that contain the given position.
3319    ///
3320    /// This method allows passing an optional [`SyntaxTheme`] to
3321    /// syntax-highlight the returned symbols.
3322    pub fn symbols_containing<T: ToOffset>(
3323        &self,
3324        position: T,
3325        theme: Option<&SyntaxTheme>,
3326    ) -> Option<Vec<OutlineItem<Anchor>>> {
3327        let position = position.to_offset(self);
3328        let mut items = self.outline_items_containing(
3329            position.saturating_sub(1)..self.len().min(position + 1),
3330            false,
3331            theme,
3332        )?;
3333        let mut prev_depth = None;
3334        items.retain(|item| {
3335            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
3336            prev_depth = Some(item.depth);
3337            result
3338        });
3339        Some(items)
3340    }
3341
3342    pub fn outline_range_containing<T: ToOffset>(&self, range: Range<T>) -> Option<Range<Point>> {
3343        let range = range.to_offset(self);
3344        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3345            grammar.outline_config.as_ref().map(|c| &c.query)
3346        });
3347        let configs = matches
3348            .grammars()
3349            .iter()
3350            .map(|g| g.outline_config.as_ref().unwrap())
3351            .collect::<Vec<_>>();
3352
3353        while let Some(mat) = matches.peek() {
3354            let config = &configs[mat.grammar_index];
3355            let containing_item_node = maybe!({
3356                let item_node = mat.captures.iter().find_map(|cap| {
3357                    if cap.index == config.item_capture_ix {
3358                        Some(cap.node)
3359                    } else {
3360                        None
3361                    }
3362                })?;
3363
3364                let item_byte_range = item_node.byte_range();
3365                if item_byte_range.end < range.start || item_byte_range.start > range.end {
3366                    None
3367                } else {
3368                    Some(item_node)
3369                }
3370            });
3371
3372            if let Some(item_node) = containing_item_node {
3373                return Some(
3374                    Point::from_ts_point(item_node.start_position())
3375                        ..Point::from_ts_point(item_node.end_position()),
3376                );
3377            }
3378
3379            matches.advance();
3380        }
3381        None
3382    }
3383
3384    pub fn outline_items_containing<T: ToOffset>(
3385        &self,
3386        range: Range<T>,
3387        include_extra_context: bool,
3388        theme: Option<&SyntaxTheme>,
3389    ) -> Option<Vec<OutlineItem<Anchor>>> {
3390        let range = range.to_offset(self);
3391        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3392            grammar.outline_config.as_ref().map(|c| &c.query)
3393        });
3394        let configs = matches
3395            .grammars()
3396            .iter()
3397            .map(|g| g.outline_config.as_ref().unwrap())
3398            .collect::<Vec<_>>();
3399
3400        let mut items = Vec::new();
3401        let mut annotation_row_ranges: Vec<Range<u32>> = Vec::new();
3402        while let Some(mat) = matches.peek() {
3403            let config = &configs[mat.grammar_index];
3404            if let Some(item) =
3405                self.next_outline_item(config, &mat, &range, include_extra_context, theme)
3406            {
3407                items.push(item);
3408            } else if let Some(capture) = mat
3409                .captures
3410                .iter()
3411                .find(|capture| Some(capture.index) == config.annotation_capture_ix)
3412            {
3413                let capture_range = capture.node.start_position()..capture.node.end_position();
3414                let mut capture_row_range =
3415                    capture_range.start.row as u32..capture_range.end.row as u32;
3416                if capture_range.end.row > capture_range.start.row && capture_range.end.column == 0
3417                {
3418                    capture_row_range.end -= 1;
3419                }
3420                if let Some(last_row_range) = annotation_row_ranges.last_mut() {
3421                    if last_row_range.end >= capture_row_range.start.saturating_sub(1) {
3422                        last_row_range.end = capture_row_range.end;
3423                    } else {
3424                        annotation_row_ranges.push(capture_row_range);
3425                    }
3426                } else {
3427                    annotation_row_ranges.push(capture_row_range);
3428                }
3429            }
3430            matches.advance();
3431        }
3432
3433        items.sort_by_key(|item| (item.range.start, Reverse(item.range.end)));
3434
3435        // Assign depths based on containment relationships and convert to anchors.
3436        let mut item_ends_stack = Vec::<Point>::new();
3437        let mut anchor_items = Vec::new();
3438        let mut annotation_row_ranges = annotation_row_ranges.into_iter().peekable();
3439        for item in items {
3440            while let Some(last_end) = item_ends_stack.last().copied() {
3441                if last_end < item.range.end {
3442                    item_ends_stack.pop();
3443                } else {
3444                    break;
3445                }
3446            }
3447
3448            let mut annotation_row_range = None;
3449            while let Some(next_annotation_row_range) = annotation_row_ranges.peek() {
3450                let row_preceding_item = item.range.start.row.saturating_sub(1);
3451                if next_annotation_row_range.end < row_preceding_item {
3452                    annotation_row_ranges.next();
3453                } else {
3454                    if next_annotation_row_range.end == row_preceding_item {
3455                        annotation_row_range = Some(next_annotation_row_range.clone());
3456                        annotation_row_ranges.next();
3457                    }
3458                    break;
3459                }
3460            }
3461
3462            anchor_items.push(OutlineItem {
3463                depth: item_ends_stack.len(),
3464                range: self.anchor_after(item.range.start)..self.anchor_before(item.range.end),
3465                text: item.text,
3466                highlight_ranges: item.highlight_ranges,
3467                name_ranges: item.name_ranges,
3468                body_range: item.body_range.map(|body_range| {
3469                    self.anchor_after(body_range.start)..self.anchor_before(body_range.end)
3470                }),
3471                annotation_range: annotation_row_range.map(|annotation_range| {
3472                    self.anchor_after(Point::new(annotation_range.start, 0))
3473                        ..self.anchor_before(Point::new(
3474                            annotation_range.end,
3475                            self.line_len(annotation_range.end),
3476                        ))
3477                }),
3478            });
3479            item_ends_stack.push(item.range.end);
3480        }
3481
3482        Some(anchor_items)
3483    }
3484
3485    fn next_outline_item(
3486        &self,
3487        config: &OutlineConfig,
3488        mat: &SyntaxMapMatch,
3489        range: &Range<usize>,
3490        include_extra_context: bool,
3491        theme: Option<&SyntaxTheme>,
3492    ) -> Option<OutlineItem<Point>> {
3493        let item_node = mat.captures.iter().find_map(|cap| {
3494            if cap.index == config.item_capture_ix {
3495                Some(cap.node)
3496            } else {
3497                None
3498            }
3499        })?;
3500
3501        let item_byte_range = item_node.byte_range();
3502        if item_byte_range.end < range.start || item_byte_range.start > range.end {
3503            return None;
3504        }
3505        let item_point_range = Point::from_ts_point(item_node.start_position())
3506            ..Point::from_ts_point(item_node.end_position());
3507
3508        let mut open_point = None;
3509        let mut close_point = None;
3510        let mut buffer_ranges = Vec::new();
3511        for capture in mat.captures {
3512            let node_is_name;
3513            if capture.index == config.name_capture_ix {
3514                node_is_name = true;
3515            } else if Some(capture.index) == config.context_capture_ix
3516                || (Some(capture.index) == config.extra_context_capture_ix && include_extra_context)
3517            {
3518                node_is_name = false;
3519            } else {
3520                if Some(capture.index) == config.open_capture_ix {
3521                    open_point = Some(Point::from_ts_point(capture.node.end_position()));
3522                } else if Some(capture.index) == config.close_capture_ix {
3523                    close_point = Some(Point::from_ts_point(capture.node.start_position()));
3524                }
3525
3526                continue;
3527            }
3528
3529            let mut range = capture.node.start_byte()..capture.node.end_byte();
3530            let start = capture.node.start_position();
3531            if capture.node.end_position().row > start.row {
3532                range.end = range.start + self.line_len(start.row as u32) as usize - start.column;
3533            }
3534
3535            if !range.is_empty() {
3536                buffer_ranges.push((range, node_is_name));
3537            }
3538        }
3539        if buffer_ranges.is_empty() {
3540            return None;
3541        }
3542        let mut text = String::new();
3543        let mut highlight_ranges = Vec::new();
3544        let mut name_ranges = Vec::new();
3545        let mut chunks = self.chunks(
3546            buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
3547            true,
3548        );
3549        let mut last_buffer_range_end = 0;
3550        for (buffer_range, is_name) in buffer_ranges {
3551            if !text.is_empty() && buffer_range.start > last_buffer_range_end {
3552                text.push(' ');
3553            }
3554            last_buffer_range_end = buffer_range.end;
3555            if is_name {
3556                let mut start = text.len();
3557                let end = start + buffer_range.len();
3558
3559                // When multiple names are captured, then the matchable text
3560                // includes the whitespace in between the names.
3561                if !name_ranges.is_empty() {
3562                    start -= 1;
3563                }
3564
3565                name_ranges.push(start..end);
3566            }
3567
3568            let mut offset = buffer_range.start;
3569            chunks.seek(buffer_range.clone());
3570            for mut chunk in chunks.by_ref() {
3571                if chunk.text.len() > buffer_range.end - offset {
3572                    chunk.text = &chunk.text[0..(buffer_range.end - offset)];
3573                    offset = buffer_range.end;
3574                } else {
3575                    offset += chunk.text.len();
3576                }
3577                let style = chunk
3578                    .syntax_highlight_id
3579                    .zip(theme)
3580                    .and_then(|(highlight, theme)| highlight.style(theme));
3581                if let Some(style) = style {
3582                    let start = text.len();
3583                    let end = start + chunk.text.len();
3584                    highlight_ranges.push((start..end, style));
3585                }
3586                text.push_str(chunk.text);
3587                if offset >= buffer_range.end {
3588                    break;
3589                }
3590            }
3591        }
3592
3593        Some(OutlineItem {
3594            depth: 0, // We'll calculate the depth later
3595            range: item_point_range,
3596            text,
3597            highlight_ranges,
3598            name_ranges,
3599            body_range: open_point.zip(close_point).map(|(start, end)| start..end),
3600            annotation_range: None,
3601        })
3602    }
3603
3604    pub fn function_body_fold_ranges<T: ToOffset>(
3605        &self,
3606        within: Range<T>,
3607    ) -> impl Iterator<Item = Range<usize>> + '_ {
3608        self.text_object_ranges(within, TreeSitterOptions::default())
3609            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
3610    }
3611
3612    /// For each grammar in the language, runs the provided
3613    /// [`tree_sitter::Query`] against the given range.
3614    pub fn matches(
3615        &self,
3616        range: Range<usize>,
3617        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
3618    ) -> SyntaxMapMatches {
3619        self.syntax.matches(range, self, query)
3620    }
3621
3622    /// Returns bracket range pairs overlapping or adjacent to `range`
3623    pub fn bracket_ranges<T: ToOffset>(
3624        &self,
3625        range: Range<T>,
3626    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3627        // Find bracket pairs that *inclusively* contain the given range.
3628        let range = range.start.to_offset(self).saturating_sub(1)
3629            ..self.len().min(range.end.to_offset(self) + 1);
3630
3631        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3632            grammar.brackets_config.as_ref().map(|c| &c.query)
3633        });
3634        let configs = matches
3635            .grammars()
3636            .iter()
3637            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
3638            .collect::<Vec<_>>();
3639
3640        iter::from_fn(move || {
3641            while let Some(mat) = matches.peek() {
3642                let mut open = None;
3643                let mut close = None;
3644                let config = &configs[mat.grammar_index];
3645                for capture in mat.captures {
3646                    if capture.index == config.open_capture_ix {
3647                        open = Some(capture.node.byte_range());
3648                    } else if capture.index == config.close_capture_ix {
3649                        close = Some(capture.node.byte_range());
3650                    }
3651                }
3652
3653                matches.advance();
3654
3655                let Some((open, close)) = open.zip(close) else {
3656                    continue;
3657                };
3658
3659                let bracket_range = open.start..=close.end;
3660                if !bracket_range.overlaps(&range) {
3661                    continue;
3662                }
3663
3664                return Some((open, close));
3665            }
3666            None
3667        })
3668    }
3669
3670    pub fn text_object_ranges<T: ToOffset>(
3671        &self,
3672        range: Range<T>,
3673        options: TreeSitterOptions,
3674    ) -> impl Iterator<Item = (Range<usize>, TextObject)> + '_ {
3675        let range = range.start.to_offset(self).saturating_sub(1)
3676            ..self.len().min(range.end.to_offset(self) + 1);
3677
3678        let mut matches =
3679            self.syntax
3680                .matches_with_options(range.clone(), &self.text, options, |grammar| {
3681                    grammar.text_object_config.as_ref().map(|c| &c.query)
3682                });
3683
3684        let configs = matches
3685            .grammars()
3686            .iter()
3687            .map(|grammar| grammar.text_object_config.as_ref())
3688            .collect::<Vec<_>>();
3689
3690        let mut captures = Vec::<(Range<usize>, TextObject)>::new();
3691
3692        iter::from_fn(move || loop {
3693            while let Some(capture) = captures.pop() {
3694                if capture.0.overlaps(&range) {
3695                    return Some(capture);
3696                }
3697            }
3698
3699            let mat = matches.peek()?;
3700
3701            let Some(config) = configs[mat.grammar_index].as_ref() else {
3702                matches.advance();
3703                continue;
3704            };
3705
3706            for capture in mat.captures {
3707                let Some(ix) = config
3708                    .text_objects_by_capture_ix
3709                    .binary_search_by_key(&capture.index, |e| e.0)
3710                    .ok()
3711                else {
3712                    continue;
3713                };
3714                let text_object = config.text_objects_by_capture_ix[ix].1;
3715                let byte_range = capture.node.byte_range();
3716
3717                let mut found = false;
3718                for (range, existing) in captures.iter_mut() {
3719                    if existing == &text_object {
3720                        range.start = range.start.min(byte_range.start);
3721                        range.end = range.end.max(byte_range.end);
3722                        found = true;
3723                        break;
3724                    }
3725                }
3726
3727                if !found {
3728                    captures.push((byte_range, text_object));
3729                }
3730            }
3731
3732            matches.advance();
3733        })
3734    }
3735
3736    /// Returns enclosing bracket ranges containing the given range
3737    pub fn enclosing_bracket_ranges<T: ToOffset>(
3738        &self,
3739        range: Range<T>,
3740    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3741        let range = range.start.to_offset(self)..range.end.to_offset(self);
3742
3743        self.bracket_ranges(range.clone())
3744            .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
3745    }
3746
3747    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3748    ///
3749    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3750    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3751        &self,
3752        range: Range<T>,
3753        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3754    ) -> Option<(Range<usize>, Range<usize>)> {
3755        let range = range.start.to_offset(self)..range.end.to_offset(self);
3756
3757        // Get the ranges of the innermost pair of brackets.
3758        let mut result: Option<(Range<usize>, Range<usize>)> = None;
3759
3760        for (open, close) in self.enclosing_bracket_ranges(range.clone()) {
3761            if let Some(range_filter) = range_filter {
3762                if !range_filter(open.clone(), close.clone()) {
3763                    continue;
3764                }
3765            }
3766
3767            let len = close.end - open.start;
3768
3769            if let Some((existing_open, existing_close)) = &result {
3770                let existing_len = existing_close.end - existing_open.start;
3771                if len > existing_len {
3772                    continue;
3773                }
3774            }
3775
3776            result = Some((open, close));
3777        }
3778
3779        result
3780    }
3781
3782    /// Returns anchor ranges for any matches of the redaction query.
3783    /// The buffer can be associated with multiple languages, and the redaction query associated with each
3784    /// will be run on the relevant section of the buffer.
3785    pub fn redacted_ranges<T: ToOffset>(
3786        &self,
3787        range: Range<T>,
3788    ) -> impl Iterator<Item = Range<usize>> + '_ {
3789        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3790        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3791            grammar
3792                .redactions_config
3793                .as_ref()
3794                .map(|config| &config.query)
3795        });
3796
3797        let configs = syntax_matches
3798            .grammars()
3799            .iter()
3800            .map(|grammar| grammar.redactions_config.as_ref())
3801            .collect::<Vec<_>>();
3802
3803        iter::from_fn(move || {
3804            let redacted_range = syntax_matches
3805                .peek()
3806                .and_then(|mat| {
3807                    configs[mat.grammar_index].and_then(|config| {
3808                        mat.captures
3809                            .iter()
3810                            .find(|capture| capture.index == config.redaction_capture_ix)
3811                    })
3812                })
3813                .map(|mat| mat.node.byte_range());
3814            syntax_matches.advance();
3815            redacted_range
3816        })
3817    }
3818
3819    pub fn injections_intersecting_range<T: ToOffset>(
3820        &self,
3821        range: Range<T>,
3822    ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3823        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3824
3825        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3826            grammar
3827                .injection_config
3828                .as_ref()
3829                .map(|config| &config.query)
3830        });
3831
3832        let configs = syntax_matches
3833            .grammars()
3834            .iter()
3835            .map(|grammar| grammar.injection_config.as_ref())
3836            .collect::<Vec<_>>();
3837
3838        iter::from_fn(move || {
3839            let ranges = syntax_matches.peek().and_then(|mat| {
3840                let config = &configs[mat.grammar_index]?;
3841                let content_capture_range = mat.captures.iter().find_map(|capture| {
3842                    if capture.index == config.content_capture_ix {
3843                        Some(capture.node.byte_range())
3844                    } else {
3845                        None
3846                    }
3847                })?;
3848                let language = self.language_at(content_capture_range.start)?;
3849                Some((content_capture_range, language))
3850            });
3851            syntax_matches.advance();
3852            ranges
3853        })
3854    }
3855
3856    pub fn runnable_ranges(
3857        &self,
3858        offset_range: Range<usize>,
3859    ) -> impl Iterator<Item = RunnableRange> + '_ {
3860        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3861            grammar.runnable_config.as_ref().map(|config| &config.query)
3862        });
3863
3864        let test_configs = syntax_matches
3865            .grammars()
3866            .iter()
3867            .map(|grammar| grammar.runnable_config.as_ref())
3868            .collect::<Vec<_>>();
3869
3870        iter::from_fn(move || loop {
3871            let mat = syntax_matches.peek()?;
3872
3873            let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3874                let mut run_range = None;
3875                let full_range = mat.captures.iter().fold(
3876                    Range {
3877                        start: usize::MAX,
3878                        end: 0,
3879                    },
3880                    |mut acc, next| {
3881                        let byte_range = next.node.byte_range();
3882                        if acc.start > byte_range.start {
3883                            acc.start = byte_range.start;
3884                        }
3885                        if acc.end < byte_range.end {
3886                            acc.end = byte_range.end;
3887                        }
3888                        acc
3889                    },
3890                );
3891                if full_range.start > full_range.end {
3892                    // We did not find a full spanning range of this match.
3893                    return None;
3894                }
3895                let extra_captures: SmallVec<[_; 1]> =
3896                    SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3897                        test_configs
3898                            .extra_captures
3899                            .get(capture.index as usize)
3900                            .cloned()
3901                            .and_then(|tag_name| match tag_name {
3902                                RunnableCapture::Named(name) => {
3903                                    Some((capture.node.byte_range(), name))
3904                                }
3905                                RunnableCapture::Run => {
3906                                    let _ = run_range.insert(capture.node.byte_range());
3907                                    None
3908                                }
3909                            })
3910                    }));
3911                let run_range = run_range?;
3912                let tags = test_configs
3913                    .query
3914                    .property_settings(mat.pattern_index)
3915                    .iter()
3916                    .filter_map(|property| {
3917                        if *property.key == *"tag" {
3918                            property
3919                                .value
3920                                .as_ref()
3921                                .map(|value| RunnableTag(value.to_string().into()))
3922                        } else {
3923                            None
3924                        }
3925                    })
3926                    .collect();
3927                let extra_captures = extra_captures
3928                    .into_iter()
3929                    .map(|(range, name)| {
3930                        (
3931                            name.to_string(),
3932                            self.text_for_range(range.clone()).collect::<String>(),
3933                        )
3934                    })
3935                    .collect();
3936                // All tags should have the same range.
3937                Some(RunnableRange {
3938                    run_range,
3939                    full_range,
3940                    runnable: Runnable {
3941                        tags,
3942                        language: mat.language,
3943                        buffer: self.remote_id(),
3944                    },
3945                    extra_captures,
3946                    buffer_id: self.remote_id(),
3947                })
3948            });
3949
3950            syntax_matches.advance();
3951            if test_range.is_some() {
3952                // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
3953                // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
3954                return test_range;
3955            }
3956        })
3957    }
3958
3959    /// Returns selections for remote peers intersecting the given range.
3960    #[allow(clippy::type_complexity)]
3961    pub fn selections_in_range(
3962        &self,
3963        range: Range<Anchor>,
3964        include_local: bool,
3965    ) -> impl Iterator<
3966        Item = (
3967            ReplicaId,
3968            bool,
3969            CursorShape,
3970            impl Iterator<Item = &Selection<Anchor>> + '_,
3971        ),
3972    > + '_ {
3973        self.remote_selections
3974            .iter()
3975            .filter(move |(replica_id, set)| {
3976                (include_local || **replica_id != self.text.replica_id())
3977                    && !set.selections.is_empty()
3978            })
3979            .map(move |(replica_id, set)| {
3980                let start_ix = match set.selections.binary_search_by(|probe| {
3981                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
3982                }) {
3983                    Ok(ix) | Err(ix) => ix,
3984                };
3985                let end_ix = match set.selections.binary_search_by(|probe| {
3986                    probe.start.cmp(&range.end, self).then(Ordering::Less)
3987                }) {
3988                    Ok(ix) | Err(ix) => ix,
3989                };
3990
3991                (
3992                    *replica_id,
3993                    set.line_mode,
3994                    set.cursor_shape,
3995                    set.selections[start_ix..end_ix].iter(),
3996                )
3997            })
3998    }
3999
4000    /// Returns if the buffer contains any diagnostics.
4001    pub fn has_diagnostics(&self) -> bool {
4002        !self.diagnostics.is_empty()
4003    }
4004
4005    /// Returns all the diagnostics intersecting the given range.
4006    pub fn diagnostics_in_range<'a, T, O>(
4007        &'a self,
4008        search_range: Range<T>,
4009        reversed: bool,
4010    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
4011    where
4012        T: 'a + Clone + ToOffset,
4013        O: 'a + FromAnchor,
4014    {
4015        let mut iterators: Vec<_> = self
4016            .diagnostics
4017            .iter()
4018            .map(|(_, collection)| {
4019                collection
4020                    .range::<T, text::Anchor>(search_range.clone(), self, true, reversed)
4021                    .peekable()
4022            })
4023            .collect();
4024
4025        std::iter::from_fn(move || {
4026            let (next_ix, _) = iterators
4027                .iter_mut()
4028                .enumerate()
4029                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
4030                .min_by(|(_, a), (_, b)| {
4031                    let cmp = a
4032                        .range
4033                        .start
4034                        .cmp(&b.range.start, self)
4035                        // when range is equal, sort by diagnostic severity
4036                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
4037                        // and stabilize order with group_id
4038                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
4039                    if reversed {
4040                        cmp.reverse()
4041                    } else {
4042                        cmp
4043                    }
4044                })?;
4045            iterators[next_ix]
4046                .next()
4047                .map(|DiagnosticEntry { range, diagnostic }| DiagnosticEntry {
4048                    diagnostic,
4049                    range: FromAnchor::from_anchor(&range.start, self)
4050                        ..FromAnchor::from_anchor(&range.end, self),
4051                })
4052        })
4053    }
4054
4055    /// Returns all the diagnostic groups associated with the given
4056    /// language server ID. If no language server ID is provided,
4057    /// all diagnostics groups are returned.
4058    pub fn diagnostic_groups(
4059        &self,
4060        language_server_id: Option<LanguageServerId>,
4061    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
4062        let mut groups = Vec::new();
4063
4064        if let Some(language_server_id) = language_server_id {
4065            if let Ok(ix) = self
4066                .diagnostics
4067                .binary_search_by_key(&language_server_id, |e| e.0)
4068            {
4069                self.diagnostics[ix]
4070                    .1
4071                    .groups(language_server_id, &mut groups, self);
4072            }
4073        } else {
4074            for (language_server_id, diagnostics) in self.diagnostics.iter() {
4075                diagnostics.groups(*language_server_id, &mut groups, self);
4076            }
4077        }
4078
4079        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
4080            let a_start = &group_a.entries[group_a.primary_ix].range.start;
4081            let b_start = &group_b.entries[group_b.primary_ix].range.start;
4082            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
4083        });
4084
4085        groups
4086    }
4087
4088    /// Returns an iterator over the diagnostics for the given group.
4089    pub fn diagnostic_group<O>(
4090        &self,
4091        group_id: usize,
4092    ) -> impl Iterator<Item = DiagnosticEntry<O>> + '_
4093    where
4094        O: FromAnchor + 'static,
4095    {
4096        self.diagnostics
4097            .iter()
4098            .flat_map(move |(_, set)| set.group(group_id, self))
4099    }
4100
4101    /// An integer version number that accounts for all updates besides
4102    /// the buffer's text itself (which is versioned via a version vector).
4103    pub fn non_text_state_update_count(&self) -> usize {
4104        self.non_text_state_update_count
4105    }
4106
4107    /// Returns a snapshot of underlying file.
4108    pub fn file(&self) -> Option<&Arc<dyn File>> {
4109        self.file.as_ref()
4110    }
4111
4112    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
4113    pub fn resolve_file_path(&self, cx: &App, include_root: bool) -> Option<PathBuf> {
4114        if let Some(file) = self.file() {
4115            if file.path().file_name().is_none() || include_root {
4116                Some(file.full_path(cx))
4117            } else {
4118                Some(file.path().to_path_buf())
4119            }
4120        } else {
4121            None
4122        }
4123    }
4124}
4125
4126fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
4127    indent_size_for_text(text.chars_at(Point::new(row, 0)))
4128}
4129
4130fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
4131    let mut result = IndentSize::spaces(0);
4132    for c in text {
4133        let kind = match c {
4134            ' ' => IndentKind::Space,
4135            '\t' => IndentKind::Tab,
4136            _ => break,
4137        };
4138        if result.len == 0 {
4139            result.kind = kind;
4140        }
4141        result.len += 1;
4142    }
4143    result
4144}
4145
4146impl Clone for BufferSnapshot {
4147    fn clone(&self) -> Self {
4148        Self {
4149            text: self.text.clone(),
4150            syntax: self.syntax.clone(),
4151            file: self.file.clone(),
4152            remote_selections: self.remote_selections.clone(),
4153            diagnostics: self.diagnostics.clone(),
4154            language: self.language.clone(),
4155            non_text_state_update_count: self.non_text_state_update_count,
4156        }
4157    }
4158}
4159
4160impl Deref for BufferSnapshot {
4161    type Target = text::BufferSnapshot;
4162
4163    fn deref(&self) -> &Self::Target {
4164        &self.text
4165    }
4166}
4167
4168unsafe impl<'a> Send for BufferChunks<'a> {}
4169
4170impl<'a> BufferChunks<'a> {
4171    pub(crate) fn new(
4172        text: &'a Rope,
4173        range: Range<usize>,
4174        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
4175        diagnostics: bool,
4176        buffer_snapshot: Option<&'a BufferSnapshot>,
4177    ) -> Self {
4178        let mut highlights = None;
4179        if let Some((captures, highlight_maps)) = syntax {
4180            highlights = Some(BufferChunkHighlights {
4181                captures,
4182                next_capture: None,
4183                stack: Default::default(),
4184                highlight_maps,
4185            })
4186        }
4187
4188        let diagnostic_endpoints = diagnostics.then(|| Vec::new().into_iter().peekable());
4189        let chunks = text.chunks_in_range(range.clone());
4190
4191        let mut this = BufferChunks {
4192            range,
4193            buffer_snapshot,
4194            chunks,
4195            diagnostic_endpoints,
4196            error_depth: 0,
4197            warning_depth: 0,
4198            information_depth: 0,
4199            hint_depth: 0,
4200            unnecessary_depth: 0,
4201            highlights,
4202        };
4203        this.initialize_diagnostic_endpoints();
4204        this
4205    }
4206
4207    /// Seeks to the given byte offset in the buffer.
4208    pub fn seek(&mut self, range: Range<usize>) {
4209        let old_range = std::mem::replace(&mut self.range, range.clone());
4210        self.chunks.set_range(self.range.clone());
4211        if let Some(highlights) = self.highlights.as_mut() {
4212            if old_range.start <= self.range.start && old_range.end >= self.range.end {
4213                // Reuse existing highlights stack, as the new range is a subrange of the old one.
4214                highlights
4215                    .stack
4216                    .retain(|(end_offset, _)| *end_offset > range.start);
4217                if let Some(capture) = &highlights.next_capture {
4218                    if range.start >= capture.node.start_byte() {
4219                        let next_capture_end = capture.node.end_byte();
4220                        if range.start < next_capture_end {
4221                            highlights.stack.push((
4222                                next_capture_end,
4223                                highlights.highlight_maps[capture.grammar_index].get(capture.index),
4224                            ));
4225                        }
4226                        highlights.next_capture.take();
4227                    }
4228                }
4229            } else if let Some(snapshot) = self.buffer_snapshot {
4230                let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
4231                *highlights = BufferChunkHighlights {
4232                    captures,
4233                    next_capture: None,
4234                    stack: Default::default(),
4235                    highlight_maps,
4236                };
4237            } else {
4238                // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
4239                // Seeking such BufferChunks is not supported.
4240                debug_assert!(false, "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot");
4241            }
4242
4243            highlights.captures.set_byte_range(self.range.clone());
4244            self.initialize_diagnostic_endpoints();
4245        }
4246    }
4247
4248    fn initialize_diagnostic_endpoints(&mut self) {
4249        if let Some(diagnostics) = self.diagnostic_endpoints.as_mut() {
4250            if let Some(buffer) = self.buffer_snapshot {
4251                let mut diagnostic_endpoints = Vec::new();
4252                for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
4253                    diagnostic_endpoints.push(DiagnosticEndpoint {
4254                        offset: entry.range.start,
4255                        is_start: true,
4256                        severity: entry.diagnostic.severity,
4257                        is_unnecessary: entry.diagnostic.is_unnecessary,
4258                    });
4259                    diagnostic_endpoints.push(DiagnosticEndpoint {
4260                        offset: entry.range.end,
4261                        is_start: false,
4262                        severity: entry.diagnostic.severity,
4263                        is_unnecessary: entry.diagnostic.is_unnecessary,
4264                    });
4265                }
4266                diagnostic_endpoints
4267                    .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
4268                *diagnostics = diagnostic_endpoints.into_iter().peekable();
4269                self.hint_depth = 0;
4270                self.error_depth = 0;
4271                self.warning_depth = 0;
4272                self.information_depth = 0;
4273            }
4274        }
4275    }
4276
4277    /// The current byte offset in the buffer.
4278    pub fn offset(&self) -> usize {
4279        self.range.start
4280    }
4281
4282    pub fn range(&self) -> Range<usize> {
4283        self.range.clone()
4284    }
4285
4286    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
4287        let depth = match endpoint.severity {
4288            DiagnosticSeverity::ERROR => &mut self.error_depth,
4289            DiagnosticSeverity::WARNING => &mut self.warning_depth,
4290            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
4291            DiagnosticSeverity::HINT => &mut self.hint_depth,
4292            _ => return,
4293        };
4294        if endpoint.is_start {
4295            *depth += 1;
4296        } else {
4297            *depth -= 1;
4298        }
4299
4300        if endpoint.is_unnecessary {
4301            if endpoint.is_start {
4302                self.unnecessary_depth += 1;
4303            } else {
4304                self.unnecessary_depth -= 1;
4305            }
4306        }
4307    }
4308
4309    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
4310        if self.error_depth > 0 {
4311            Some(DiagnosticSeverity::ERROR)
4312        } else if self.warning_depth > 0 {
4313            Some(DiagnosticSeverity::WARNING)
4314        } else if self.information_depth > 0 {
4315            Some(DiagnosticSeverity::INFORMATION)
4316        } else if self.hint_depth > 0 {
4317            Some(DiagnosticSeverity::HINT)
4318        } else {
4319            None
4320        }
4321    }
4322
4323    fn current_code_is_unnecessary(&self) -> bool {
4324        self.unnecessary_depth > 0
4325    }
4326}
4327
4328impl<'a> Iterator for BufferChunks<'a> {
4329    type Item = Chunk<'a>;
4330
4331    fn next(&mut self) -> Option<Self::Item> {
4332        let mut next_capture_start = usize::MAX;
4333        let mut next_diagnostic_endpoint = usize::MAX;
4334
4335        if let Some(highlights) = self.highlights.as_mut() {
4336            while let Some((parent_capture_end, _)) = highlights.stack.last() {
4337                if *parent_capture_end <= self.range.start {
4338                    highlights.stack.pop();
4339                } else {
4340                    break;
4341                }
4342            }
4343
4344            if highlights.next_capture.is_none() {
4345                highlights.next_capture = highlights.captures.next();
4346            }
4347
4348            while let Some(capture) = highlights.next_capture.as_ref() {
4349                if self.range.start < capture.node.start_byte() {
4350                    next_capture_start = capture.node.start_byte();
4351                    break;
4352                } else {
4353                    let highlight_id =
4354                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
4355                    highlights
4356                        .stack
4357                        .push((capture.node.end_byte(), highlight_id));
4358                    highlights.next_capture = highlights.captures.next();
4359                }
4360            }
4361        }
4362
4363        let mut diagnostic_endpoints = std::mem::take(&mut self.diagnostic_endpoints);
4364        if let Some(diagnostic_endpoints) = diagnostic_endpoints.as_mut() {
4365            while let Some(endpoint) = diagnostic_endpoints.peek().copied() {
4366                if endpoint.offset <= self.range.start {
4367                    self.update_diagnostic_depths(endpoint);
4368                    diagnostic_endpoints.next();
4369                } else {
4370                    next_diagnostic_endpoint = endpoint.offset;
4371                    break;
4372                }
4373            }
4374        }
4375        self.diagnostic_endpoints = diagnostic_endpoints;
4376
4377        if let Some(chunk) = self.chunks.peek() {
4378            let chunk_start = self.range.start;
4379            let mut chunk_end = (self.chunks.offset() + chunk.len())
4380                .min(next_capture_start)
4381                .min(next_diagnostic_endpoint);
4382            let mut highlight_id = None;
4383            if let Some(highlights) = self.highlights.as_ref() {
4384                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
4385                    chunk_end = chunk_end.min(*parent_capture_end);
4386                    highlight_id = Some(*parent_highlight_id);
4387                }
4388            }
4389
4390            let slice =
4391                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
4392            self.range.start = chunk_end;
4393            if self.range.start == self.chunks.offset() + chunk.len() {
4394                self.chunks.next().unwrap();
4395            }
4396
4397            Some(Chunk {
4398                text: slice,
4399                syntax_highlight_id: highlight_id,
4400                diagnostic_severity: self.current_diagnostic_severity(),
4401                is_unnecessary: self.current_code_is_unnecessary(),
4402                ..Default::default()
4403            })
4404        } else {
4405            None
4406        }
4407    }
4408}
4409
4410impl operation_queue::Operation for Operation {
4411    fn lamport_timestamp(&self) -> clock::Lamport {
4412        match self {
4413            Operation::Buffer(_) => {
4414                unreachable!("buffer operations should never be deferred at this layer")
4415            }
4416            Operation::UpdateDiagnostics {
4417                lamport_timestamp, ..
4418            }
4419            | Operation::UpdateSelections {
4420                lamport_timestamp, ..
4421            }
4422            | Operation::UpdateCompletionTriggers {
4423                lamport_timestamp, ..
4424            } => *lamport_timestamp,
4425        }
4426    }
4427}
4428
4429impl Default for Diagnostic {
4430    fn default() -> Self {
4431        Self {
4432            source: Default::default(),
4433            code: None,
4434            severity: DiagnosticSeverity::ERROR,
4435            message: Default::default(),
4436            group_id: 0,
4437            is_primary: false,
4438            is_disk_based: false,
4439            is_unnecessary: false,
4440            data: None,
4441        }
4442    }
4443}
4444
4445impl IndentSize {
4446    /// Returns an [`IndentSize`] representing the given spaces.
4447    pub fn spaces(len: u32) -> Self {
4448        Self {
4449            len,
4450            kind: IndentKind::Space,
4451        }
4452    }
4453
4454    /// Returns an [`IndentSize`] representing a tab.
4455    pub fn tab() -> Self {
4456        Self {
4457            len: 1,
4458            kind: IndentKind::Tab,
4459        }
4460    }
4461
4462    /// An iterator over the characters represented by this [`IndentSize`].
4463    pub fn chars(&self) -> impl Iterator<Item = char> {
4464        iter::repeat(self.char()).take(self.len as usize)
4465    }
4466
4467    /// The character representation of this [`IndentSize`].
4468    pub fn char(&self) -> char {
4469        match self.kind {
4470            IndentKind::Space => ' ',
4471            IndentKind::Tab => '\t',
4472        }
4473    }
4474
4475    /// Consumes the current [`IndentSize`] and returns a new one that has
4476    /// been shrunk or enlarged by the given size along the given direction.
4477    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4478        match direction {
4479            Ordering::Less => {
4480                if self.kind == size.kind && self.len >= size.len {
4481                    self.len -= size.len;
4482                }
4483            }
4484            Ordering::Equal => {}
4485            Ordering::Greater => {
4486                if self.len == 0 {
4487                    self = size;
4488                } else if self.kind == size.kind {
4489                    self.len += size.len;
4490                }
4491            }
4492        }
4493        self
4494    }
4495
4496    pub fn len_with_expanded_tabs(&self, tab_size: NonZeroU32) -> usize {
4497        match self.kind {
4498            IndentKind::Space => self.len as usize,
4499            IndentKind::Tab => self.len as usize * tab_size.get() as usize,
4500        }
4501    }
4502}
4503
4504#[cfg(any(test, feature = "test-support"))]
4505pub struct TestFile {
4506    pub path: Arc<Path>,
4507    pub root_name: String,
4508}
4509
4510#[cfg(any(test, feature = "test-support"))]
4511impl File for TestFile {
4512    fn path(&self) -> &Arc<Path> {
4513        &self.path
4514    }
4515
4516    fn full_path(&self, _: &gpui::App) -> PathBuf {
4517        PathBuf::from(&self.root_name).join(self.path.as_ref())
4518    }
4519
4520    fn as_local(&self) -> Option<&dyn LocalFile> {
4521        None
4522    }
4523
4524    fn disk_state(&self) -> DiskState {
4525        unimplemented!()
4526    }
4527
4528    fn file_name<'a>(&'a self, _: &'a gpui::App) -> &'a std::ffi::OsStr {
4529        self.path().file_name().unwrap_or(self.root_name.as_ref())
4530    }
4531
4532    fn worktree_id(&self, _: &App) -> WorktreeId {
4533        WorktreeId::from_usize(0)
4534    }
4535
4536    fn as_any(&self) -> &dyn std::any::Any {
4537        unimplemented!()
4538    }
4539
4540    fn to_proto(&self, _: &App) -> rpc::proto::File {
4541        unimplemented!()
4542    }
4543
4544    fn is_private(&self) -> bool {
4545        false
4546    }
4547}
4548
4549pub(crate) fn contiguous_ranges(
4550    values: impl Iterator<Item = u32>,
4551    max_len: usize,
4552) -> impl Iterator<Item = Range<u32>> {
4553    let mut values = values;
4554    let mut current_range: Option<Range<u32>> = None;
4555    std::iter::from_fn(move || loop {
4556        if let Some(value) = values.next() {
4557            if let Some(range) = &mut current_range {
4558                if value == range.end && range.len() < max_len {
4559                    range.end += 1;
4560                    continue;
4561                }
4562            }
4563
4564            let prev_range = current_range.clone();
4565            current_range = Some(value..(value + 1));
4566            if prev_range.is_some() {
4567                return prev_range;
4568            }
4569        } else {
4570            return current_range.take();
4571        }
4572    })
4573}
4574
4575#[derive(Default, Debug)]
4576pub struct CharClassifier {
4577    scope: Option<LanguageScope>,
4578    for_completion: bool,
4579    ignore_punctuation: bool,
4580}
4581
4582impl CharClassifier {
4583    pub fn new(scope: Option<LanguageScope>) -> Self {
4584        Self {
4585            scope,
4586            for_completion: false,
4587            ignore_punctuation: false,
4588        }
4589    }
4590
4591    pub fn for_completion(self, for_completion: bool) -> Self {
4592        Self {
4593            for_completion,
4594            ..self
4595        }
4596    }
4597
4598    pub fn ignore_punctuation(self, ignore_punctuation: bool) -> Self {
4599        Self {
4600            ignore_punctuation,
4601            ..self
4602        }
4603    }
4604
4605    pub fn is_whitespace(&self, c: char) -> bool {
4606        self.kind(c) == CharKind::Whitespace
4607    }
4608
4609    pub fn is_word(&self, c: char) -> bool {
4610        self.kind(c) == CharKind::Word
4611    }
4612
4613    pub fn is_punctuation(&self, c: char) -> bool {
4614        self.kind(c) == CharKind::Punctuation
4615    }
4616
4617    pub fn kind_with(&self, c: char, ignore_punctuation: bool) -> CharKind {
4618        if c.is_whitespace() {
4619            return CharKind::Whitespace;
4620        } else if c.is_alphanumeric() || c == '_' {
4621            return CharKind::Word;
4622        }
4623
4624        if let Some(scope) = &self.scope {
4625            if let Some(characters) = scope.word_characters() {
4626                if characters.contains(&c) {
4627                    if c == '-' && !self.for_completion && !ignore_punctuation {
4628                        return CharKind::Punctuation;
4629                    }
4630                    return CharKind::Word;
4631                }
4632            }
4633        }
4634
4635        if ignore_punctuation {
4636            CharKind::Word
4637        } else {
4638            CharKind::Punctuation
4639        }
4640    }
4641
4642    pub fn kind(&self, c: char) -> CharKind {
4643        self.kind_with(c, self.ignore_punctuation)
4644    }
4645}
4646
4647/// Find all of the ranges of whitespace that occur at the ends of lines
4648/// in the given rope.
4649///
4650/// This could also be done with a regex search, but this implementation
4651/// avoids copying text.
4652pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4653    let mut ranges = Vec::new();
4654
4655    let mut offset = 0;
4656    let mut prev_chunk_trailing_whitespace_range = 0..0;
4657    for chunk in rope.chunks() {
4658        let mut prev_line_trailing_whitespace_range = 0..0;
4659        for (i, line) in chunk.split('\n').enumerate() {
4660            let line_end_offset = offset + line.len();
4661            let trimmed_line_len = line.trim_end_matches([' ', '\t']).len();
4662            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4663
4664            if i == 0 && trimmed_line_len == 0 {
4665                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4666            }
4667            if !prev_line_trailing_whitespace_range.is_empty() {
4668                ranges.push(prev_line_trailing_whitespace_range);
4669            }
4670
4671            offset = line_end_offset + 1;
4672            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4673        }
4674
4675        offset -= 1;
4676        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4677    }
4678
4679    if !prev_chunk_trailing_whitespace_range.is_empty() {
4680        ranges.push(prev_chunk_trailing_whitespace_range);
4681    }
4682
4683    ranges
4684}