buffer.rs

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