buffer.rs

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