buffer.rs

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