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