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 /// language preferences.
2763    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2764        indent_size_for_line(self, row)
2765    }
2766    /// Returns [`IndentSize`] for a given position that respects user settings
2767    /// and language preferences.
2768    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &App) -> IndentSize {
2769        let settings = language_settings(
2770            self.language_at(position).map(|l| l.name()),
2771            self.file(),
2772            cx,
2773        );
2774        if settings.hard_tabs {
2775            IndentSize::tab()
2776        } else {
2777            IndentSize::spaces(settings.tab_size.get())
2778        }
2779    }
2780
2781    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2782    /// is passed in as `single_indent_size`.
2783    pub fn suggested_indents(
2784        &self,
2785        rows: impl Iterator<Item = u32>,
2786        single_indent_size: IndentSize,
2787    ) -> BTreeMap<u32, IndentSize> {
2788        let mut result = BTreeMap::new();
2789
2790        for row_range in contiguous_ranges(rows, 10) {
2791            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2792                Some(suggestions) => suggestions,
2793                _ => break,
2794            };
2795
2796            for (row, suggestion) in row_range.zip(suggestions) {
2797                let indent_size = if let Some(suggestion) = suggestion {
2798                    result
2799                        .get(&suggestion.basis_row)
2800                        .copied()
2801                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2802                        .with_delta(suggestion.delta, single_indent_size)
2803                } else {
2804                    self.indent_size_for_line(row)
2805                };
2806
2807                result.insert(row, indent_size);
2808            }
2809        }
2810
2811        result
2812    }
2813
2814    fn suggest_autoindents(
2815        &self,
2816        row_range: Range<u32>,
2817    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2818        let config = &self.language.as_ref()?.config;
2819        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2820
2821        // Find the suggested indentation ranges based on the syntax tree.
2822        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2823        let end = Point::new(row_range.end, 0);
2824        let range = (start..end).to_offset(&self.text);
2825        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2826            Some(&grammar.indents_config.as_ref()?.query)
2827        });
2828        let indent_configs = matches
2829            .grammars()
2830            .iter()
2831            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2832            .collect::<Vec<_>>();
2833
2834        let mut indent_ranges = Vec::<Range<Point>>::new();
2835        let mut outdent_positions = Vec::<Point>::new();
2836        while let Some(mat) = matches.peek() {
2837            let mut start: Option<Point> = None;
2838            let mut end: Option<Point> = None;
2839
2840            let config = &indent_configs[mat.grammar_index];
2841            for capture in mat.captures {
2842                if capture.index == config.indent_capture_ix {
2843                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2844                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2845                } else if Some(capture.index) == config.start_capture_ix {
2846                    start = Some(Point::from_ts_point(capture.node.end_position()));
2847                } else if Some(capture.index) == config.end_capture_ix {
2848                    end = Some(Point::from_ts_point(capture.node.start_position()));
2849                } else if Some(capture.index) == config.outdent_capture_ix {
2850                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2851                }
2852            }
2853
2854            matches.advance();
2855            if let Some((start, end)) = start.zip(end) {
2856                if start.row == end.row {
2857                    continue;
2858                }
2859
2860                let range = start..end;
2861                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2862                    Err(ix) => indent_ranges.insert(ix, range),
2863                    Ok(ix) => {
2864                        let prev_range = &mut indent_ranges[ix];
2865                        prev_range.end = prev_range.end.max(range.end);
2866                    }
2867                }
2868            }
2869        }
2870
2871        let mut error_ranges = Vec::<Range<Point>>::new();
2872        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2873            grammar.error_query.as_ref()
2874        });
2875        while let Some(mat) = matches.peek() {
2876            let node = mat.captures[0].node;
2877            let start = Point::from_ts_point(node.start_position());
2878            let end = Point::from_ts_point(node.end_position());
2879            let range = start..end;
2880            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2881                Ok(ix) | Err(ix) => ix,
2882            };
2883            let mut end_ix = ix;
2884            while let Some(existing_range) = error_ranges.get(end_ix) {
2885                if existing_range.end < end {
2886                    end_ix += 1;
2887                } else {
2888                    break;
2889                }
2890            }
2891            error_ranges.splice(ix..end_ix, [range]);
2892            matches.advance();
2893        }
2894
2895        outdent_positions.sort();
2896        for outdent_position in outdent_positions {
2897            // find the innermost indent range containing this outdent_position
2898            // set its end to the outdent position
2899            if let Some(range_to_truncate) = indent_ranges
2900                .iter_mut()
2901                .filter(|indent_range| indent_range.contains(&outdent_position))
2902                .last()
2903            {
2904                range_to_truncate.end = outdent_position;
2905            }
2906        }
2907
2908        // Find the suggested indentation increases and decreased based on regexes.
2909        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2910        self.for_each_line(
2911            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2912                ..Point::new(row_range.end, 0),
2913            |row, line| {
2914                if config
2915                    .decrease_indent_pattern
2916                    .as_ref()
2917                    .map_or(false, |regex| regex.is_match(line))
2918                {
2919                    indent_change_rows.push((row, Ordering::Less));
2920                }
2921                if config
2922                    .increase_indent_pattern
2923                    .as_ref()
2924                    .map_or(false, |regex| regex.is_match(line))
2925                {
2926                    indent_change_rows.push((row + 1, Ordering::Greater));
2927                }
2928            },
2929        );
2930
2931        let mut indent_changes = indent_change_rows.into_iter().peekable();
2932        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2933            prev_non_blank_row.unwrap_or(0)
2934        } else {
2935            row_range.start.saturating_sub(1)
2936        };
2937        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2938        Some(row_range.map(move |row| {
2939            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2940
2941            let mut indent_from_prev_row = false;
2942            let mut outdent_from_prev_row = false;
2943            let mut outdent_to_row = u32::MAX;
2944            let mut from_regex = false;
2945
2946            while let Some((indent_row, delta)) = indent_changes.peek() {
2947                match indent_row.cmp(&row) {
2948                    Ordering::Equal => match delta {
2949                        Ordering::Less => {
2950                            from_regex = true;
2951                            outdent_from_prev_row = true
2952                        }
2953                        Ordering::Greater => {
2954                            indent_from_prev_row = true;
2955                            from_regex = true
2956                        }
2957                        _ => {}
2958                    },
2959
2960                    Ordering::Greater => break,
2961                    Ordering::Less => {}
2962                }
2963
2964                indent_changes.next();
2965            }
2966
2967            for range in &indent_ranges {
2968                if range.start.row >= row {
2969                    break;
2970                }
2971                if range.start.row == prev_row && range.end > row_start {
2972                    indent_from_prev_row = true;
2973                }
2974                if range.end > prev_row_start && range.end <= row_start {
2975                    outdent_to_row = outdent_to_row.min(range.start.row);
2976                }
2977            }
2978
2979            let within_error = error_ranges
2980                .iter()
2981                .any(|e| e.start.row < row && e.end > row_start);
2982
2983            let suggestion = if outdent_to_row == prev_row
2984                || (outdent_from_prev_row && indent_from_prev_row)
2985            {
2986                Some(IndentSuggestion {
2987                    basis_row: prev_row,
2988                    delta: Ordering::Equal,
2989                    within_error: within_error && !from_regex,
2990                })
2991            } else if indent_from_prev_row {
2992                Some(IndentSuggestion {
2993                    basis_row: prev_row,
2994                    delta: Ordering::Greater,
2995                    within_error: within_error && !from_regex,
2996                })
2997            } else if outdent_to_row < prev_row {
2998                Some(IndentSuggestion {
2999                    basis_row: outdent_to_row,
3000                    delta: Ordering::Equal,
3001                    within_error: within_error && !from_regex,
3002                })
3003            } else if outdent_from_prev_row {
3004                Some(IndentSuggestion {
3005                    basis_row: prev_row,
3006                    delta: Ordering::Less,
3007                    within_error: within_error && !from_regex,
3008                })
3009            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
3010            {
3011                Some(IndentSuggestion {
3012                    basis_row: prev_row,
3013                    delta: Ordering::Equal,
3014                    within_error: within_error && !from_regex,
3015                })
3016            } else {
3017                None
3018            };
3019
3020            prev_row = row;
3021            prev_row_start = row_start;
3022            suggestion
3023        }))
3024    }
3025
3026    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
3027        while row > 0 {
3028            row -= 1;
3029            if !self.is_line_blank(row) {
3030                return Some(row);
3031            }
3032        }
3033        None
3034    }
3035
3036    fn get_highlights(&self, range: Range<usize>) -> (SyntaxMapCaptures, Vec<HighlightMap>) {
3037        let captures = self.syntax.captures(range, &self.text, |grammar| {
3038            grammar.highlights_query.as_ref()
3039        });
3040        let highlight_maps = captures
3041            .grammars()
3042            .iter()
3043            .map(|grammar| grammar.highlight_map())
3044            .collect();
3045        (captures, highlight_maps)
3046    }
3047
3048    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
3049    /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
3050    /// returned in chunks where each chunk has a single syntax highlighting style and
3051    /// diagnostic status.
3052    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
3053        let range = range.start.to_offset(self)..range.end.to_offset(self);
3054
3055        let mut syntax = None;
3056        if language_aware {
3057            syntax = Some(self.get_highlights(range.clone()));
3058        }
3059        // We want to look at diagnostic spans only when iterating over language-annotated chunks.
3060        let diagnostics = language_aware;
3061        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostics, Some(self))
3062    }
3063
3064    pub fn highlighted_text_for_range<T: ToOffset>(
3065        &self,
3066        range: Range<T>,
3067        override_style: Option<HighlightStyle>,
3068        syntax_theme: &SyntaxTheme,
3069    ) -> HighlightedText {
3070        HighlightedText::from_buffer_range(
3071            range,
3072            &self.text,
3073            &self.syntax,
3074            override_style,
3075            syntax_theme,
3076        )
3077    }
3078
3079    /// Invokes the given callback for each line of text in the given range of the buffer.
3080    /// Uses callback to avoid allocating a string for each line.
3081    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
3082        let mut line = String::new();
3083        let mut row = range.start.row;
3084        for chunk in self
3085            .as_rope()
3086            .chunks_in_range(range.to_offset(self))
3087            .chain(["\n"])
3088        {
3089            for (newline_ix, text) in chunk.split('\n').enumerate() {
3090                if newline_ix > 0 {
3091                    callback(row, &line);
3092                    row += 1;
3093                    line.clear();
3094                }
3095                line.push_str(text);
3096            }
3097        }
3098    }
3099
3100    /// Iterates over every [`SyntaxLayer`] in the buffer.
3101    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
3102        self.syntax
3103            .layers_for_range(0..self.len(), &self.text, true)
3104    }
3105
3106    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
3107        let offset = position.to_offset(self);
3108        self.syntax
3109            .layers_for_range(offset..offset, &self.text, false)
3110            .filter(|l| l.node().end_byte() > offset)
3111            .last()
3112    }
3113
3114    /// Returns the main [`Language`].
3115    pub fn language(&self) -> Option<&Arc<Language>> {
3116        self.language.as_ref()
3117    }
3118
3119    /// Returns the [`Language`] at the given location.
3120    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
3121        self.syntax_layer_at(position)
3122            .map(|info| info.language)
3123            .or(self.language.as_ref())
3124    }
3125
3126    /// Returns the settings for the language at the given location.
3127    pub fn settings_at<'a, D: ToOffset>(
3128        &'a self,
3129        position: D,
3130        cx: &'a App,
3131    ) -> Cow<'a, LanguageSettings> {
3132        language_settings(
3133            self.language_at(position).map(|l| l.name()),
3134            self.file.as_ref(),
3135            cx,
3136        )
3137    }
3138
3139    pub fn char_classifier_at<T: ToOffset>(&self, point: T) -> CharClassifier {
3140        CharClassifier::new(self.language_scope_at(point))
3141    }
3142
3143    /// Returns the [`LanguageScope`] at the given location.
3144    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
3145        let offset = position.to_offset(self);
3146        let mut scope = None;
3147        let mut smallest_range: Option<Range<usize>> = None;
3148
3149        // Use the layer that has the smallest node intersecting the given point.
3150        for layer in self
3151            .syntax
3152            .layers_for_range(offset..offset, &self.text, false)
3153        {
3154            let mut cursor = layer.node().walk();
3155
3156            let mut range = None;
3157            loop {
3158                let child_range = cursor.node().byte_range();
3159                if !child_range.to_inclusive().contains(&offset) {
3160                    break;
3161                }
3162
3163                range = Some(child_range);
3164                if cursor.goto_first_child_for_byte(offset).is_none() {
3165                    break;
3166                }
3167            }
3168
3169            if let Some(range) = range {
3170                if smallest_range
3171                    .as_ref()
3172                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
3173                {
3174                    smallest_range = Some(range);
3175                    scope = Some(LanguageScope {
3176                        language: layer.language.clone(),
3177                        override_id: layer.override_id(offset, &self.text),
3178                    });
3179                }
3180            }
3181        }
3182
3183        scope.or_else(|| {
3184            self.language.clone().map(|language| LanguageScope {
3185                language,
3186                override_id: None,
3187            })
3188        })
3189    }
3190
3191    /// Returns a tuple of the range and character kind of the word
3192    /// surrounding the given position.
3193    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
3194        let mut start = start.to_offset(self);
3195        let mut end = start;
3196        let mut next_chars = self.chars_at(start).peekable();
3197        let mut prev_chars = self.reversed_chars_at(start).peekable();
3198
3199        let classifier = self.char_classifier_at(start);
3200        let word_kind = cmp::max(
3201            prev_chars.peek().copied().map(|c| classifier.kind(c)),
3202            next_chars.peek().copied().map(|c| classifier.kind(c)),
3203        );
3204
3205        for ch in prev_chars {
3206            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3207                start -= ch.len_utf8();
3208            } else {
3209                break;
3210            }
3211        }
3212
3213        for ch in next_chars {
3214            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3215                end += ch.len_utf8();
3216            } else {
3217                break;
3218            }
3219        }
3220
3221        (start..end, word_kind)
3222    }
3223
3224    /// Returns the closest syntax node enclosing the given range.
3225    pub fn syntax_ancestor<'a, T: ToOffset>(
3226        &'a self,
3227        range: Range<T>,
3228    ) -> Option<tree_sitter::Node<'a>> {
3229        let range = range.start.to_offset(self)..range.end.to_offset(self);
3230        let mut result: Option<tree_sitter::Node<'a>> = None;
3231        'outer: for layer in self
3232            .syntax
3233            .layers_for_range(range.clone(), &self.text, true)
3234        {
3235            let mut cursor = layer.node().walk();
3236
3237            // Descend to the first leaf that touches the start of the range,
3238            // and if the range is non-empty, extends beyond the start.
3239            while cursor.goto_first_child_for_byte(range.start).is_some() {
3240                if !range.is_empty() && cursor.node().end_byte() == range.start {
3241                    cursor.goto_next_sibling();
3242                }
3243            }
3244
3245            // Ascend to the smallest ancestor that strictly contains the range.
3246            loop {
3247                let node_range = cursor.node().byte_range();
3248                if node_range.start <= range.start
3249                    && node_range.end >= range.end
3250                    && node_range.len() > range.len()
3251                {
3252                    break;
3253                }
3254                if !cursor.goto_parent() {
3255                    continue 'outer;
3256                }
3257            }
3258
3259            let left_node = cursor.node();
3260            let mut layer_result = left_node;
3261
3262            // For an empty range, try to find another node immediately to the right of the range.
3263            if left_node.end_byte() == range.start {
3264                let mut right_node = None;
3265                while !cursor.goto_next_sibling() {
3266                    if !cursor.goto_parent() {
3267                        break;
3268                    }
3269                }
3270
3271                while cursor.node().start_byte() == range.start {
3272                    right_node = Some(cursor.node());
3273                    if !cursor.goto_first_child() {
3274                        break;
3275                    }
3276                }
3277
3278                // If there is a candidate node on both sides of the (empty) range, then
3279                // decide between the two by favoring a named node over an anonymous token.
3280                // If both nodes are the same in that regard, favor the right one.
3281                if let Some(right_node) = right_node {
3282                    if right_node.is_named() || !left_node.is_named() {
3283                        layer_result = right_node;
3284                    }
3285                }
3286            }
3287
3288            if let Some(previous_result) = &result {
3289                if previous_result.byte_range().len() < layer_result.byte_range().len() {
3290                    continue;
3291                }
3292            }
3293            result = Some(layer_result);
3294        }
3295
3296        result
3297    }
3298
3299    /// Returns the outline for the buffer.
3300    ///
3301    /// This method allows passing an optional [`SyntaxTheme`] to
3302    /// syntax-highlight the returned symbols.
3303    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3304        self.outline_items_containing(0..self.len(), true, theme)
3305            .map(Outline::new)
3306    }
3307
3308    /// Returns all the symbols that contain the given position.
3309    ///
3310    /// This method allows passing an optional [`SyntaxTheme`] to
3311    /// syntax-highlight the returned symbols.
3312    pub fn symbols_containing<T: ToOffset>(
3313        &self,
3314        position: T,
3315        theme: Option<&SyntaxTheme>,
3316    ) -> Option<Vec<OutlineItem<Anchor>>> {
3317        let position = position.to_offset(self);
3318        let mut items = self.outline_items_containing(
3319            position.saturating_sub(1)..self.len().min(position + 1),
3320            false,
3321            theme,
3322        )?;
3323        let mut prev_depth = None;
3324        items.retain(|item| {
3325            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
3326            prev_depth = Some(item.depth);
3327            result
3328        });
3329        Some(items)
3330    }
3331
3332    pub fn outline_range_containing<T: ToOffset>(&self, range: Range<T>) -> Option<Range<Point>> {
3333        let range = range.to_offset(self);
3334        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3335            grammar.outline_config.as_ref().map(|c| &c.query)
3336        });
3337        let configs = matches
3338            .grammars()
3339            .iter()
3340            .map(|g| g.outline_config.as_ref().unwrap())
3341            .collect::<Vec<_>>();
3342
3343        while let Some(mat) = matches.peek() {
3344            let config = &configs[mat.grammar_index];
3345            let containing_item_node = maybe!({
3346                let item_node = mat.captures.iter().find_map(|cap| {
3347                    if cap.index == config.item_capture_ix {
3348                        Some(cap.node)
3349                    } else {
3350                        None
3351                    }
3352                })?;
3353
3354                let item_byte_range = item_node.byte_range();
3355                if item_byte_range.end < range.start || item_byte_range.start > range.end {
3356                    None
3357                } else {
3358                    Some(item_node)
3359                }
3360            });
3361
3362            if let Some(item_node) = containing_item_node {
3363                return Some(
3364                    Point::from_ts_point(item_node.start_position())
3365                        ..Point::from_ts_point(item_node.end_position()),
3366                );
3367            }
3368
3369            matches.advance();
3370        }
3371        None
3372    }
3373
3374    pub fn outline_items_containing<T: ToOffset>(
3375        &self,
3376        range: Range<T>,
3377        include_extra_context: bool,
3378        theme: Option<&SyntaxTheme>,
3379    ) -> Option<Vec<OutlineItem<Anchor>>> {
3380        let range = range.to_offset(self);
3381        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3382            grammar.outline_config.as_ref().map(|c| &c.query)
3383        });
3384        let configs = matches
3385            .grammars()
3386            .iter()
3387            .map(|g| g.outline_config.as_ref().unwrap())
3388            .collect::<Vec<_>>();
3389
3390        let mut items = Vec::new();
3391        let mut annotation_row_ranges: Vec<Range<u32>> = Vec::new();
3392        while let Some(mat) = matches.peek() {
3393            let config = &configs[mat.grammar_index];
3394            if let Some(item) =
3395                self.next_outline_item(config, &mat, &range, include_extra_context, theme)
3396            {
3397                items.push(item);
3398            } else if let Some(capture) = mat
3399                .captures
3400                .iter()
3401                .find(|capture| Some(capture.index) == config.annotation_capture_ix)
3402            {
3403                let capture_range = capture.node.start_position()..capture.node.end_position();
3404                let mut capture_row_range =
3405                    capture_range.start.row as u32..capture_range.end.row as u32;
3406                if capture_range.end.row > capture_range.start.row && capture_range.end.column == 0
3407                {
3408                    capture_row_range.end -= 1;
3409                }
3410                if let Some(last_row_range) = annotation_row_ranges.last_mut() {
3411                    if last_row_range.end >= capture_row_range.start.saturating_sub(1) {
3412                        last_row_range.end = capture_row_range.end;
3413                    } else {
3414                        annotation_row_ranges.push(capture_row_range);
3415                    }
3416                } else {
3417                    annotation_row_ranges.push(capture_row_range);
3418                }
3419            }
3420            matches.advance();
3421        }
3422
3423        items.sort_by_key(|item| (item.range.start, Reverse(item.range.end)));
3424
3425        // Assign depths based on containment relationships and convert to anchors.
3426        let mut item_ends_stack = Vec::<Point>::new();
3427        let mut anchor_items = Vec::new();
3428        let mut annotation_row_ranges = annotation_row_ranges.into_iter().peekable();
3429        for item in items {
3430            while let Some(last_end) = item_ends_stack.last().copied() {
3431                if last_end < item.range.end {
3432                    item_ends_stack.pop();
3433                } else {
3434                    break;
3435                }
3436            }
3437
3438            let mut annotation_row_range = None;
3439            while let Some(next_annotation_row_range) = annotation_row_ranges.peek() {
3440                let row_preceding_item = item.range.start.row.saturating_sub(1);
3441                if next_annotation_row_range.end < row_preceding_item {
3442                    annotation_row_ranges.next();
3443                } else {
3444                    if next_annotation_row_range.end == row_preceding_item {
3445                        annotation_row_range = Some(next_annotation_row_range.clone());
3446                        annotation_row_ranges.next();
3447                    }
3448                    break;
3449                }
3450            }
3451
3452            anchor_items.push(OutlineItem {
3453                depth: item_ends_stack.len(),
3454                range: self.anchor_after(item.range.start)..self.anchor_before(item.range.end),
3455                text: item.text,
3456                highlight_ranges: item.highlight_ranges,
3457                name_ranges: item.name_ranges,
3458                body_range: item.body_range.map(|body_range| {
3459                    self.anchor_after(body_range.start)..self.anchor_before(body_range.end)
3460                }),
3461                annotation_range: annotation_row_range.map(|annotation_range| {
3462                    self.anchor_after(Point::new(annotation_range.start, 0))
3463                        ..self.anchor_before(Point::new(
3464                            annotation_range.end,
3465                            self.line_len(annotation_range.end),
3466                        ))
3467                }),
3468            });
3469            item_ends_stack.push(item.range.end);
3470        }
3471
3472        Some(anchor_items)
3473    }
3474
3475    fn next_outline_item(
3476        &self,
3477        config: &OutlineConfig,
3478        mat: &SyntaxMapMatch,
3479        range: &Range<usize>,
3480        include_extra_context: bool,
3481        theme: Option<&SyntaxTheme>,
3482    ) -> Option<OutlineItem<Point>> {
3483        let item_node = mat.captures.iter().find_map(|cap| {
3484            if cap.index == config.item_capture_ix {
3485                Some(cap.node)
3486            } else {
3487                None
3488            }
3489        })?;
3490
3491        let item_byte_range = item_node.byte_range();
3492        if item_byte_range.end < range.start || item_byte_range.start > range.end {
3493            return None;
3494        }
3495        let item_point_range = Point::from_ts_point(item_node.start_position())
3496            ..Point::from_ts_point(item_node.end_position());
3497
3498        let mut open_point = None;
3499        let mut close_point = None;
3500        let mut buffer_ranges = Vec::new();
3501        for capture in mat.captures {
3502            let node_is_name;
3503            if capture.index == config.name_capture_ix {
3504                node_is_name = true;
3505            } else if Some(capture.index) == config.context_capture_ix
3506                || (Some(capture.index) == config.extra_context_capture_ix && include_extra_context)
3507            {
3508                node_is_name = false;
3509            } else {
3510                if Some(capture.index) == config.open_capture_ix {
3511                    open_point = Some(Point::from_ts_point(capture.node.end_position()));
3512                } else if Some(capture.index) == config.close_capture_ix {
3513                    close_point = Some(Point::from_ts_point(capture.node.start_position()));
3514                }
3515
3516                continue;
3517            }
3518
3519            let mut range = capture.node.start_byte()..capture.node.end_byte();
3520            let start = capture.node.start_position();
3521            if capture.node.end_position().row > start.row {
3522                range.end = range.start + self.line_len(start.row as u32) as usize - start.column;
3523            }
3524
3525            if !range.is_empty() {
3526                buffer_ranges.push((range, node_is_name));
3527            }
3528        }
3529        if buffer_ranges.is_empty() {
3530            return None;
3531        }
3532        let mut text = String::new();
3533        let mut highlight_ranges = Vec::new();
3534        let mut name_ranges = Vec::new();
3535        let mut chunks = self.chunks(
3536            buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
3537            true,
3538        );
3539        let mut last_buffer_range_end = 0;
3540        for (buffer_range, is_name) in buffer_ranges {
3541            if !text.is_empty() && buffer_range.start > last_buffer_range_end {
3542                text.push(' ');
3543            }
3544            last_buffer_range_end = buffer_range.end;
3545            if is_name {
3546                let mut start = text.len();
3547                let end = start + buffer_range.len();
3548
3549                // When multiple names are captured, then the matchable text
3550                // includes the whitespace in between the names.
3551                if !name_ranges.is_empty() {
3552                    start -= 1;
3553                }
3554
3555                name_ranges.push(start..end);
3556            }
3557
3558            let mut offset = buffer_range.start;
3559            chunks.seek(buffer_range.clone());
3560            for mut chunk in chunks.by_ref() {
3561                if chunk.text.len() > buffer_range.end - offset {
3562                    chunk.text = &chunk.text[0..(buffer_range.end - offset)];
3563                    offset = buffer_range.end;
3564                } else {
3565                    offset += chunk.text.len();
3566                }
3567                let style = chunk
3568                    .syntax_highlight_id
3569                    .zip(theme)
3570                    .and_then(|(highlight, theme)| highlight.style(theme));
3571                if let Some(style) = style {
3572                    let start = text.len();
3573                    let end = start + chunk.text.len();
3574                    highlight_ranges.push((start..end, style));
3575                }
3576                text.push_str(chunk.text);
3577                if offset >= buffer_range.end {
3578                    break;
3579                }
3580            }
3581        }
3582
3583        Some(OutlineItem {
3584            depth: 0, // We'll calculate the depth later
3585            range: item_point_range,
3586            text,
3587            highlight_ranges,
3588            name_ranges,
3589            body_range: open_point.zip(close_point).map(|(start, end)| start..end),
3590            annotation_range: None,
3591        })
3592    }
3593
3594    pub fn function_body_fold_ranges<T: ToOffset>(
3595        &self,
3596        within: Range<T>,
3597    ) -> impl Iterator<Item = Range<usize>> + '_ {
3598        self.text_object_ranges(within, TreeSitterOptions::default())
3599            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
3600    }
3601
3602    /// For each grammar in the language, runs the provided
3603    /// [`tree_sitter::Query`] against the given range.
3604    pub fn matches(
3605        &self,
3606        range: Range<usize>,
3607        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
3608    ) -> SyntaxMapMatches {
3609        self.syntax.matches(range, self, query)
3610    }
3611
3612    /// Returns bracket range pairs overlapping or adjacent to `range`
3613    pub fn bracket_ranges<T: ToOffset>(
3614        &self,
3615        range: Range<T>,
3616    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3617        // Find bracket pairs that *inclusively* contain the given range.
3618        let range = range.start.to_offset(self).saturating_sub(1)
3619            ..self.len().min(range.end.to_offset(self) + 1);
3620
3621        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3622            grammar.brackets_config.as_ref().map(|c| &c.query)
3623        });
3624        let configs = matches
3625            .grammars()
3626            .iter()
3627            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
3628            .collect::<Vec<_>>();
3629
3630        iter::from_fn(move || {
3631            while let Some(mat) = matches.peek() {
3632                let mut open = None;
3633                let mut close = None;
3634                let config = &configs[mat.grammar_index];
3635                for capture in mat.captures {
3636                    if capture.index == config.open_capture_ix {
3637                        open = Some(capture.node.byte_range());
3638                    } else if capture.index == config.close_capture_ix {
3639                        close = Some(capture.node.byte_range());
3640                    }
3641                }
3642
3643                matches.advance();
3644
3645                let Some((open, close)) = open.zip(close) else {
3646                    continue;
3647                };
3648
3649                let bracket_range = open.start..=close.end;
3650                if !bracket_range.overlaps(&range) {
3651                    continue;
3652                }
3653
3654                return Some((open, close));
3655            }
3656            None
3657        })
3658    }
3659
3660    pub fn text_object_ranges<T: ToOffset>(
3661        &self,
3662        range: Range<T>,
3663        options: TreeSitterOptions,
3664    ) -> impl Iterator<Item = (Range<usize>, TextObject)> + '_ {
3665        let range = range.start.to_offset(self).saturating_sub(1)
3666            ..self.len().min(range.end.to_offset(self) + 1);
3667
3668        let mut matches =
3669            self.syntax
3670                .matches_with_options(range.clone(), &self.text, options, |grammar| {
3671                    grammar.text_object_config.as_ref().map(|c| &c.query)
3672                });
3673
3674        let configs = matches
3675            .grammars()
3676            .iter()
3677            .map(|grammar| grammar.text_object_config.as_ref())
3678            .collect::<Vec<_>>();
3679
3680        let mut captures = Vec::<(Range<usize>, TextObject)>::new();
3681
3682        iter::from_fn(move || loop {
3683            while let Some(capture) = captures.pop() {
3684                if capture.0.overlaps(&range) {
3685                    return Some(capture);
3686                }
3687            }
3688
3689            let mat = matches.peek()?;
3690
3691            let Some(config) = configs[mat.grammar_index].as_ref() else {
3692                matches.advance();
3693                continue;
3694            };
3695
3696            for capture in mat.captures {
3697                let Some(ix) = config
3698                    .text_objects_by_capture_ix
3699                    .binary_search_by_key(&capture.index, |e| e.0)
3700                    .ok()
3701                else {
3702                    continue;
3703                };
3704                let text_object = config.text_objects_by_capture_ix[ix].1;
3705                let byte_range = capture.node.byte_range();
3706
3707                let mut found = false;
3708                for (range, existing) in captures.iter_mut() {
3709                    if existing == &text_object {
3710                        range.start = range.start.min(byte_range.start);
3711                        range.end = range.end.max(byte_range.end);
3712                        found = true;
3713                        break;
3714                    }
3715                }
3716
3717                if !found {
3718                    captures.push((byte_range, text_object));
3719                }
3720            }
3721
3722            matches.advance();
3723        })
3724    }
3725
3726    /// Returns enclosing bracket ranges containing the given range
3727    pub fn enclosing_bracket_ranges<T: ToOffset>(
3728        &self,
3729        range: Range<T>,
3730    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3731        let range = range.start.to_offset(self)..range.end.to_offset(self);
3732
3733        self.bracket_ranges(range.clone())
3734            .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
3735    }
3736
3737    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3738    ///
3739    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3740    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3741        &self,
3742        range: Range<T>,
3743        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3744    ) -> Option<(Range<usize>, Range<usize>)> {
3745        let range = range.start.to_offset(self)..range.end.to_offset(self);
3746
3747        // Get the ranges of the innermost pair of brackets.
3748        let mut result: Option<(Range<usize>, Range<usize>)> = None;
3749
3750        for (open, close) in self.enclosing_bracket_ranges(range.clone()) {
3751            if let Some(range_filter) = range_filter {
3752                if !range_filter(open.clone(), close.clone()) {
3753                    continue;
3754                }
3755            }
3756
3757            let len = close.end - open.start;
3758
3759            if let Some((existing_open, existing_close)) = &result {
3760                let existing_len = existing_close.end - existing_open.start;
3761                if len > existing_len {
3762                    continue;
3763                }
3764            }
3765
3766            result = Some((open, close));
3767        }
3768
3769        result
3770    }
3771
3772    /// Returns anchor ranges for any matches of the redaction query.
3773    /// The buffer can be associated with multiple languages, and the redaction query associated with each
3774    /// will be run on the relevant section of the buffer.
3775    pub fn redacted_ranges<T: ToOffset>(
3776        &self,
3777        range: Range<T>,
3778    ) -> impl Iterator<Item = Range<usize>> + '_ {
3779        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3780        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3781            grammar
3782                .redactions_config
3783                .as_ref()
3784                .map(|config| &config.query)
3785        });
3786
3787        let configs = syntax_matches
3788            .grammars()
3789            .iter()
3790            .map(|grammar| grammar.redactions_config.as_ref())
3791            .collect::<Vec<_>>();
3792
3793        iter::from_fn(move || {
3794            let redacted_range = syntax_matches
3795                .peek()
3796                .and_then(|mat| {
3797                    configs[mat.grammar_index].and_then(|config| {
3798                        mat.captures
3799                            .iter()
3800                            .find(|capture| capture.index == config.redaction_capture_ix)
3801                    })
3802                })
3803                .map(|mat| mat.node.byte_range());
3804            syntax_matches.advance();
3805            redacted_range
3806        })
3807    }
3808
3809    pub fn injections_intersecting_range<T: ToOffset>(
3810        &self,
3811        range: Range<T>,
3812    ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3813        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3814
3815        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3816            grammar
3817                .injection_config
3818                .as_ref()
3819                .map(|config| &config.query)
3820        });
3821
3822        let configs = syntax_matches
3823            .grammars()
3824            .iter()
3825            .map(|grammar| grammar.injection_config.as_ref())
3826            .collect::<Vec<_>>();
3827
3828        iter::from_fn(move || {
3829            let ranges = syntax_matches.peek().and_then(|mat| {
3830                let config = &configs[mat.grammar_index]?;
3831                let content_capture_range = mat.captures.iter().find_map(|capture| {
3832                    if capture.index == config.content_capture_ix {
3833                        Some(capture.node.byte_range())
3834                    } else {
3835                        None
3836                    }
3837                })?;
3838                let language = self.language_at(content_capture_range.start)?;
3839                Some((content_capture_range, language))
3840            });
3841            syntax_matches.advance();
3842            ranges
3843        })
3844    }
3845
3846    pub fn runnable_ranges(
3847        &self,
3848        offset_range: Range<usize>,
3849    ) -> impl Iterator<Item = RunnableRange> + '_ {
3850        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3851            grammar.runnable_config.as_ref().map(|config| &config.query)
3852        });
3853
3854        let test_configs = syntax_matches
3855            .grammars()
3856            .iter()
3857            .map(|grammar| grammar.runnable_config.as_ref())
3858            .collect::<Vec<_>>();
3859
3860        iter::from_fn(move || loop {
3861            let mat = syntax_matches.peek()?;
3862
3863            let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3864                let mut run_range = None;
3865                let full_range = mat.captures.iter().fold(
3866                    Range {
3867                        start: usize::MAX,
3868                        end: 0,
3869                    },
3870                    |mut acc, next| {
3871                        let byte_range = next.node.byte_range();
3872                        if acc.start > byte_range.start {
3873                            acc.start = byte_range.start;
3874                        }
3875                        if acc.end < byte_range.end {
3876                            acc.end = byte_range.end;
3877                        }
3878                        acc
3879                    },
3880                );
3881                if full_range.start > full_range.end {
3882                    // We did not find a full spanning range of this match.
3883                    return None;
3884                }
3885                let extra_captures: SmallVec<[_; 1]> =
3886                    SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3887                        test_configs
3888                            .extra_captures
3889                            .get(capture.index as usize)
3890                            .cloned()
3891                            .and_then(|tag_name| match tag_name {
3892                                RunnableCapture::Named(name) => {
3893                                    Some((capture.node.byte_range(), name))
3894                                }
3895                                RunnableCapture::Run => {
3896                                    let _ = run_range.insert(capture.node.byte_range());
3897                                    None
3898                                }
3899                            })
3900                    }));
3901                let run_range = run_range?;
3902                let tags = test_configs
3903                    .query
3904                    .property_settings(mat.pattern_index)
3905                    .iter()
3906                    .filter_map(|property| {
3907                        if *property.key == *"tag" {
3908                            property
3909                                .value
3910                                .as_ref()
3911                                .map(|value| RunnableTag(value.to_string().into()))
3912                        } else {
3913                            None
3914                        }
3915                    })
3916                    .collect();
3917                let extra_captures = extra_captures
3918                    .into_iter()
3919                    .map(|(range, name)| {
3920                        (
3921                            name.to_string(),
3922                            self.text_for_range(range.clone()).collect::<String>(),
3923                        )
3924                    })
3925                    .collect();
3926                // All tags should have the same range.
3927                Some(RunnableRange {
3928                    run_range,
3929                    full_range,
3930                    runnable: Runnable {
3931                        tags,
3932                        language: mat.language,
3933                        buffer: self.remote_id(),
3934                    },
3935                    extra_captures,
3936                    buffer_id: self.remote_id(),
3937                })
3938            });
3939
3940            syntax_matches.advance();
3941            if test_range.is_some() {
3942                // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
3943                // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
3944                return test_range;
3945            }
3946        })
3947    }
3948
3949    /// Returns selections for remote peers intersecting the given range.
3950    #[allow(clippy::type_complexity)]
3951    pub fn selections_in_range(
3952        &self,
3953        range: Range<Anchor>,
3954        include_local: bool,
3955    ) -> impl Iterator<
3956        Item = (
3957            ReplicaId,
3958            bool,
3959            CursorShape,
3960            impl Iterator<Item = &Selection<Anchor>> + '_,
3961        ),
3962    > + '_ {
3963        self.remote_selections
3964            .iter()
3965            .filter(move |(replica_id, set)| {
3966                (include_local || **replica_id != self.text.replica_id())
3967                    && !set.selections.is_empty()
3968            })
3969            .map(move |(replica_id, set)| {
3970                let start_ix = match set.selections.binary_search_by(|probe| {
3971                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
3972                }) {
3973                    Ok(ix) | Err(ix) => ix,
3974                };
3975                let end_ix = match set.selections.binary_search_by(|probe| {
3976                    probe.start.cmp(&range.end, self).then(Ordering::Less)
3977                }) {
3978                    Ok(ix) | Err(ix) => ix,
3979                };
3980
3981                (
3982                    *replica_id,
3983                    set.line_mode,
3984                    set.cursor_shape,
3985                    set.selections[start_ix..end_ix].iter(),
3986                )
3987            })
3988    }
3989
3990    /// Returns if the buffer contains any diagnostics.
3991    pub fn has_diagnostics(&self) -> bool {
3992        !self.diagnostics.is_empty()
3993    }
3994
3995    /// Returns all the diagnostics intersecting the given range.
3996    pub fn diagnostics_in_range<'a, T, O>(
3997        &'a self,
3998        search_range: Range<T>,
3999        reversed: bool,
4000    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
4001    where
4002        T: 'a + Clone + ToOffset,
4003        O: 'a + FromAnchor,
4004    {
4005        let mut iterators: Vec<_> = self
4006            .diagnostics
4007            .iter()
4008            .map(|(_, collection)| {
4009                collection
4010                    .range::<T, text::Anchor>(search_range.clone(), self, true, reversed)
4011                    .peekable()
4012            })
4013            .collect();
4014
4015        std::iter::from_fn(move || {
4016            let (next_ix, _) = iterators
4017                .iter_mut()
4018                .enumerate()
4019                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
4020                .min_by(|(_, a), (_, b)| {
4021                    let cmp = a
4022                        .range
4023                        .start
4024                        .cmp(&b.range.start, self)
4025                        // when range is equal, sort by diagnostic severity
4026                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
4027                        // and stabilize order with group_id
4028                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
4029                    if reversed {
4030                        cmp.reverse()
4031                    } else {
4032                        cmp
4033                    }
4034                })?;
4035            iterators[next_ix]
4036                .next()
4037                .map(|DiagnosticEntry { range, diagnostic }| DiagnosticEntry {
4038                    diagnostic,
4039                    range: FromAnchor::from_anchor(&range.start, self)
4040                        ..FromAnchor::from_anchor(&range.end, self),
4041                })
4042        })
4043    }
4044
4045    /// Returns all the diagnostic groups associated with the given
4046    /// language server ID. If no language server ID is provided,
4047    /// all diagnostics groups are returned.
4048    pub fn diagnostic_groups(
4049        &self,
4050        language_server_id: Option<LanguageServerId>,
4051    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
4052        let mut groups = Vec::new();
4053
4054        if let Some(language_server_id) = language_server_id {
4055            if let Ok(ix) = self
4056                .diagnostics
4057                .binary_search_by_key(&language_server_id, |e| e.0)
4058            {
4059                self.diagnostics[ix]
4060                    .1
4061                    .groups(language_server_id, &mut groups, self);
4062            }
4063        } else {
4064            for (language_server_id, diagnostics) in self.diagnostics.iter() {
4065                diagnostics.groups(*language_server_id, &mut groups, self);
4066            }
4067        }
4068
4069        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
4070            let a_start = &group_a.entries[group_a.primary_ix].range.start;
4071            let b_start = &group_b.entries[group_b.primary_ix].range.start;
4072            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
4073        });
4074
4075        groups
4076    }
4077
4078    /// Returns an iterator over the diagnostics for the given group.
4079    pub fn diagnostic_group<O>(
4080        &self,
4081        group_id: usize,
4082    ) -> impl Iterator<Item = DiagnosticEntry<O>> + '_
4083    where
4084        O: FromAnchor + 'static,
4085    {
4086        self.diagnostics
4087            .iter()
4088            .flat_map(move |(_, set)| set.group(group_id, self))
4089    }
4090
4091    /// An integer version number that accounts for all updates besides
4092    /// the buffer's text itself (which is versioned via a version vector).
4093    pub fn non_text_state_update_count(&self) -> usize {
4094        self.non_text_state_update_count
4095    }
4096
4097    /// Returns a snapshot of underlying file.
4098    pub fn file(&self) -> Option<&Arc<dyn File>> {
4099        self.file.as_ref()
4100    }
4101
4102    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
4103    pub fn resolve_file_path(&self, cx: &App, include_root: bool) -> Option<PathBuf> {
4104        if let Some(file) = self.file() {
4105            if file.path().file_name().is_none() || include_root {
4106                Some(file.full_path(cx))
4107            } else {
4108                Some(file.path().to_path_buf())
4109            }
4110        } else {
4111            None
4112        }
4113    }
4114}
4115
4116fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
4117    indent_size_for_text(text.chars_at(Point::new(row, 0)))
4118}
4119
4120fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
4121    let mut result = IndentSize::spaces(0);
4122    for c in text {
4123        let kind = match c {
4124            ' ' => IndentKind::Space,
4125            '\t' => IndentKind::Tab,
4126            _ => break,
4127        };
4128        if result.len == 0 {
4129            result.kind = kind;
4130        }
4131        result.len += 1;
4132    }
4133    result
4134}
4135
4136impl Clone for BufferSnapshot {
4137    fn clone(&self) -> Self {
4138        Self {
4139            text: self.text.clone(),
4140            syntax: self.syntax.clone(),
4141            file: self.file.clone(),
4142            remote_selections: self.remote_selections.clone(),
4143            diagnostics: self.diagnostics.clone(),
4144            language: self.language.clone(),
4145            non_text_state_update_count: self.non_text_state_update_count,
4146        }
4147    }
4148}
4149
4150impl Deref for BufferSnapshot {
4151    type Target = text::BufferSnapshot;
4152
4153    fn deref(&self) -> &Self::Target {
4154        &self.text
4155    }
4156}
4157
4158unsafe impl<'a> Send for BufferChunks<'a> {}
4159
4160impl<'a> BufferChunks<'a> {
4161    pub(crate) fn new(
4162        text: &'a Rope,
4163        range: Range<usize>,
4164        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
4165        diagnostics: bool,
4166        buffer_snapshot: Option<&'a BufferSnapshot>,
4167    ) -> Self {
4168        let mut highlights = None;
4169        if let Some((captures, highlight_maps)) = syntax {
4170            highlights = Some(BufferChunkHighlights {
4171                captures,
4172                next_capture: None,
4173                stack: Default::default(),
4174                highlight_maps,
4175            })
4176        }
4177
4178        let diagnostic_endpoints = diagnostics.then(|| Vec::new().into_iter().peekable());
4179        let chunks = text.chunks_in_range(range.clone());
4180
4181        let mut this = BufferChunks {
4182            range,
4183            buffer_snapshot,
4184            chunks,
4185            diagnostic_endpoints,
4186            error_depth: 0,
4187            warning_depth: 0,
4188            information_depth: 0,
4189            hint_depth: 0,
4190            unnecessary_depth: 0,
4191            highlights,
4192        };
4193        this.initialize_diagnostic_endpoints();
4194        this
4195    }
4196
4197    /// Seeks to the given byte offset in the buffer.
4198    pub fn seek(&mut self, range: Range<usize>) {
4199        let old_range = std::mem::replace(&mut self.range, range.clone());
4200        self.chunks.set_range(self.range.clone());
4201        if let Some(highlights) = self.highlights.as_mut() {
4202            if old_range.start <= self.range.start && old_range.end >= self.range.end {
4203                // Reuse existing highlights stack, as the new range is a subrange of the old one.
4204                highlights
4205                    .stack
4206                    .retain(|(end_offset, _)| *end_offset > range.start);
4207                if let Some(capture) = &highlights.next_capture {
4208                    if range.start >= capture.node.start_byte() {
4209                        let next_capture_end = capture.node.end_byte();
4210                        if range.start < next_capture_end {
4211                            highlights.stack.push((
4212                                next_capture_end,
4213                                highlights.highlight_maps[capture.grammar_index].get(capture.index),
4214                            ));
4215                        }
4216                        highlights.next_capture.take();
4217                    }
4218                }
4219            } else if let Some(snapshot) = self.buffer_snapshot {
4220                let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
4221                *highlights = BufferChunkHighlights {
4222                    captures,
4223                    next_capture: None,
4224                    stack: Default::default(),
4225                    highlight_maps,
4226                };
4227            } else {
4228                // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
4229                // Seeking such BufferChunks is not supported.
4230                debug_assert!(false, "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot");
4231            }
4232
4233            highlights.captures.set_byte_range(self.range.clone());
4234            self.initialize_diagnostic_endpoints();
4235        }
4236    }
4237
4238    fn initialize_diagnostic_endpoints(&mut self) {
4239        if let Some(diagnostics) = self.diagnostic_endpoints.as_mut() {
4240            if let Some(buffer) = self.buffer_snapshot {
4241                let mut diagnostic_endpoints = Vec::new();
4242                for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
4243                    diagnostic_endpoints.push(DiagnosticEndpoint {
4244                        offset: entry.range.start,
4245                        is_start: true,
4246                        severity: entry.diagnostic.severity,
4247                        is_unnecessary: entry.diagnostic.is_unnecessary,
4248                    });
4249                    diagnostic_endpoints.push(DiagnosticEndpoint {
4250                        offset: entry.range.end,
4251                        is_start: false,
4252                        severity: entry.diagnostic.severity,
4253                        is_unnecessary: entry.diagnostic.is_unnecessary,
4254                    });
4255                }
4256                diagnostic_endpoints
4257                    .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
4258                *diagnostics = diagnostic_endpoints.into_iter().peekable();
4259                self.hint_depth = 0;
4260                self.error_depth = 0;
4261                self.warning_depth = 0;
4262                self.information_depth = 0;
4263            }
4264        }
4265    }
4266
4267    /// The current byte offset in the buffer.
4268    pub fn offset(&self) -> usize {
4269        self.range.start
4270    }
4271
4272    pub fn range(&self) -> Range<usize> {
4273        self.range.clone()
4274    }
4275
4276    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
4277        let depth = match endpoint.severity {
4278            DiagnosticSeverity::ERROR => &mut self.error_depth,
4279            DiagnosticSeverity::WARNING => &mut self.warning_depth,
4280            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
4281            DiagnosticSeverity::HINT => &mut self.hint_depth,
4282            _ => return,
4283        };
4284        if endpoint.is_start {
4285            *depth += 1;
4286        } else {
4287            *depth -= 1;
4288        }
4289
4290        if endpoint.is_unnecessary {
4291            if endpoint.is_start {
4292                self.unnecessary_depth += 1;
4293            } else {
4294                self.unnecessary_depth -= 1;
4295            }
4296        }
4297    }
4298
4299    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
4300        if self.error_depth > 0 {
4301            Some(DiagnosticSeverity::ERROR)
4302        } else if self.warning_depth > 0 {
4303            Some(DiagnosticSeverity::WARNING)
4304        } else if self.information_depth > 0 {
4305            Some(DiagnosticSeverity::INFORMATION)
4306        } else if self.hint_depth > 0 {
4307            Some(DiagnosticSeverity::HINT)
4308        } else {
4309            None
4310        }
4311    }
4312
4313    fn current_code_is_unnecessary(&self) -> bool {
4314        self.unnecessary_depth > 0
4315    }
4316}
4317
4318impl<'a> Iterator for BufferChunks<'a> {
4319    type Item = Chunk<'a>;
4320
4321    fn next(&mut self) -> Option<Self::Item> {
4322        let mut next_capture_start = usize::MAX;
4323        let mut next_diagnostic_endpoint = usize::MAX;
4324
4325        if let Some(highlights) = self.highlights.as_mut() {
4326            while let Some((parent_capture_end, _)) = highlights.stack.last() {
4327                if *parent_capture_end <= self.range.start {
4328                    highlights.stack.pop();
4329                } else {
4330                    break;
4331                }
4332            }
4333
4334            if highlights.next_capture.is_none() {
4335                highlights.next_capture = highlights.captures.next();
4336            }
4337
4338            while let Some(capture) = highlights.next_capture.as_ref() {
4339                if self.range.start < capture.node.start_byte() {
4340                    next_capture_start = capture.node.start_byte();
4341                    break;
4342                } else {
4343                    let highlight_id =
4344                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
4345                    highlights
4346                        .stack
4347                        .push((capture.node.end_byte(), highlight_id));
4348                    highlights.next_capture = highlights.captures.next();
4349                }
4350            }
4351        }
4352
4353        let mut diagnostic_endpoints = std::mem::take(&mut self.diagnostic_endpoints);
4354        if let Some(diagnostic_endpoints) = diagnostic_endpoints.as_mut() {
4355            while let Some(endpoint) = diagnostic_endpoints.peek().copied() {
4356                if endpoint.offset <= self.range.start {
4357                    self.update_diagnostic_depths(endpoint);
4358                    diagnostic_endpoints.next();
4359                } else {
4360                    next_diagnostic_endpoint = endpoint.offset;
4361                    break;
4362                }
4363            }
4364        }
4365        self.diagnostic_endpoints = diagnostic_endpoints;
4366
4367        if let Some(chunk) = self.chunks.peek() {
4368            let chunk_start = self.range.start;
4369            let mut chunk_end = (self.chunks.offset() + chunk.len())
4370                .min(next_capture_start)
4371                .min(next_diagnostic_endpoint);
4372            let mut highlight_id = None;
4373            if let Some(highlights) = self.highlights.as_ref() {
4374                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
4375                    chunk_end = chunk_end.min(*parent_capture_end);
4376                    highlight_id = Some(*parent_highlight_id);
4377                }
4378            }
4379
4380            let slice =
4381                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
4382            self.range.start = chunk_end;
4383            if self.range.start == self.chunks.offset() + chunk.len() {
4384                self.chunks.next().unwrap();
4385            }
4386
4387            Some(Chunk {
4388                text: slice,
4389                syntax_highlight_id: highlight_id,
4390                diagnostic_severity: self.current_diagnostic_severity(),
4391                is_unnecessary: self.current_code_is_unnecessary(),
4392                ..Default::default()
4393            })
4394        } else {
4395            None
4396        }
4397    }
4398}
4399
4400impl operation_queue::Operation for Operation {
4401    fn lamport_timestamp(&self) -> clock::Lamport {
4402        match self {
4403            Operation::Buffer(_) => {
4404                unreachable!("buffer operations should never be deferred at this layer")
4405            }
4406            Operation::UpdateDiagnostics {
4407                lamport_timestamp, ..
4408            }
4409            | Operation::UpdateSelections {
4410                lamport_timestamp, ..
4411            }
4412            | Operation::UpdateCompletionTriggers {
4413                lamport_timestamp, ..
4414            } => *lamport_timestamp,
4415        }
4416    }
4417}
4418
4419impl Default for Diagnostic {
4420    fn default() -> Self {
4421        Self {
4422            source: Default::default(),
4423            code: None,
4424            severity: DiagnosticSeverity::ERROR,
4425            message: Default::default(),
4426            group_id: 0,
4427            is_primary: false,
4428            is_disk_based: false,
4429            is_unnecessary: false,
4430            data: None,
4431        }
4432    }
4433}
4434
4435impl IndentSize {
4436    /// Returns an [`IndentSize`] representing the given spaces.
4437    pub fn spaces(len: u32) -> Self {
4438        Self {
4439            len,
4440            kind: IndentKind::Space,
4441        }
4442    }
4443
4444    /// Returns an [`IndentSize`] representing a tab.
4445    pub fn tab() -> Self {
4446        Self {
4447            len: 1,
4448            kind: IndentKind::Tab,
4449        }
4450    }
4451
4452    /// An iterator over the characters represented by this [`IndentSize`].
4453    pub fn chars(&self) -> impl Iterator<Item = char> {
4454        iter::repeat(self.char()).take(self.len as usize)
4455    }
4456
4457    /// The character representation of this [`IndentSize`].
4458    pub fn char(&self) -> char {
4459        match self.kind {
4460            IndentKind::Space => ' ',
4461            IndentKind::Tab => '\t',
4462        }
4463    }
4464
4465    /// Consumes the current [`IndentSize`] and returns a new one that has
4466    /// been shrunk or enlarged by the given size along the given direction.
4467    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4468        match direction {
4469            Ordering::Less => {
4470                if self.kind == size.kind && self.len >= size.len {
4471                    self.len -= size.len;
4472                }
4473            }
4474            Ordering::Equal => {}
4475            Ordering::Greater => {
4476                if self.len == 0 {
4477                    self = size;
4478                } else if self.kind == size.kind {
4479                    self.len += size.len;
4480                }
4481            }
4482        }
4483        self
4484    }
4485
4486    pub fn len_with_expanded_tabs(&self, tab_size: NonZeroU32) -> usize {
4487        match self.kind {
4488            IndentKind::Space => self.len as usize,
4489            IndentKind::Tab => self.len as usize * tab_size.get() as usize,
4490        }
4491    }
4492}
4493
4494#[cfg(any(test, feature = "test-support"))]
4495pub struct TestFile {
4496    pub path: Arc<Path>,
4497    pub root_name: String,
4498}
4499
4500#[cfg(any(test, feature = "test-support"))]
4501impl File for TestFile {
4502    fn path(&self) -> &Arc<Path> {
4503        &self.path
4504    }
4505
4506    fn full_path(&self, _: &gpui::App) -> PathBuf {
4507        PathBuf::from(&self.root_name).join(self.path.as_ref())
4508    }
4509
4510    fn as_local(&self) -> Option<&dyn LocalFile> {
4511        None
4512    }
4513
4514    fn disk_state(&self) -> DiskState {
4515        unimplemented!()
4516    }
4517
4518    fn file_name<'a>(&'a self, _: &'a gpui::App) -> &'a std::ffi::OsStr {
4519        self.path().file_name().unwrap_or(self.root_name.as_ref())
4520    }
4521
4522    fn worktree_id(&self, _: &App) -> WorktreeId {
4523        WorktreeId::from_usize(0)
4524    }
4525
4526    fn as_any(&self) -> &dyn std::any::Any {
4527        unimplemented!()
4528    }
4529
4530    fn to_proto(&self, _: &App) -> rpc::proto::File {
4531        unimplemented!()
4532    }
4533
4534    fn is_private(&self) -> bool {
4535        false
4536    }
4537}
4538
4539pub(crate) fn contiguous_ranges(
4540    values: impl Iterator<Item = u32>,
4541    max_len: usize,
4542) -> impl Iterator<Item = Range<u32>> {
4543    let mut values = values;
4544    let mut current_range: Option<Range<u32>> = None;
4545    std::iter::from_fn(move || loop {
4546        if let Some(value) = values.next() {
4547            if let Some(range) = &mut current_range {
4548                if value == range.end && range.len() < max_len {
4549                    range.end += 1;
4550                    continue;
4551                }
4552            }
4553
4554            let prev_range = current_range.clone();
4555            current_range = Some(value..(value + 1));
4556            if prev_range.is_some() {
4557                return prev_range;
4558            }
4559        } else {
4560            return current_range.take();
4561        }
4562    })
4563}
4564
4565#[derive(Default, Debug)]
4566pub struct CharClassifier {
4567    scope: Option<LanguageScope>,
4568    for_completion: bool,
4569    ignore_punctuation: bool,
4570}
4571
4572impl CharClassifier {
4573    pub fn new(scope: Option<LanguageScope>) -> Self {
4574        Self {
4575            scope,
4576            for_completion: false,
4577            ignore_punctuation: false,
4578        }
4579    }
4580
4581    pub fn for_completion(self, for_completion: bool) -> Self {
4582        Self {
4583            for_completion,
4584            ..self
4585        }
4586    }
4587
4588    pub fn ignore_punctuation(self, ignore_punctuation: bool) -> Self {
4589        Self {
4590            ignore_punctuation,
4591            ..self
4592        }
4593    }
4594
4595    pub fn is_whitespace(&self, c: char) -> bool {
4596        self.kind(c) == CharKind::Whitespace
4597    }
4598
4599    pub fn is_word(&self, c: char) -> bool {
4600        self.kind(c) == CharKind::Word
4601    }
4602
4603    pub fn is_punctuation(&self, c: char) -> bool {
4604        self.kind(c) == CharKind::Punctuation
4605    }
4606
4607    pub fn kind_with(&self, c: char, ignore_punctuation: bool) -> CharKind {
4608        if c.is_whitespace() {
4609            return CharKind::Whitespace;
4610        } else if c.is_alphanumeric() || c == '_' {
4611            return CharKind::Word;
4612        }
4613
4614        if let Some(scope) = &self.scope {
4615            if let Some(characters) = scope.word_characters() {
4616                if characters.contains(&c) {
4617                    if c == '-' && !self.for_completion && !ignore_punctuation {
4618                        return CharKind::Punctuation;
4619                    }
4620                    return CharKind::Word;
4621                }
4622            }
4623        }
4624
4625        if ignore_punctuation {
4626            CharKind::Word
4627        } else {
4628            CharKind::Punctuation
4629        }
4630    }
4631
4632    pub fn kind(&self, c: char) -> CharKind {
4633        self.kind_with(c, self.ignore_punctuation)
4634    }
4635}
4636
4637/// Find all of the ranges of whitespace that occur at the ends of lines
4638/// in the given rope.
4639///
4640/// This could also be done with a regex search, but this implementation
4641/// avoids copying text.
4642pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4643    let mut ranges = Vec::new();
4644
4645    let mut offset = 0;
4646    let mut prev_chunk_trailing_whitespace_range = 0..0;
4647    for chunk in rope.chunks() {
4648        let mut prev_line_trailing_whitespace_range = 0..0;
4649        for (i, line) in chunk.split('\n').enumerate() {
4650            let line_end_offset = offset + line.len();
4651            let trimmed_line_len = line.trim_end_matches([' ', '\t']).len();
4652            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4653
4654            if i == 0 && trimmed_line_len == 0 {
4655                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4656            }
4657            if !prev_line_trailing_whitespace_range.is_empty() {
4658                ranges.push(prev_line_trailing_whitespace_range);
4659            }
4660
4661            offset = line_end_offset + 1;
4662            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4663        }
4664
4665        offset -= 1;
4666        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4667    }
4668
4669    if !prev_chunk_trailing_whitespace_range.is_empty() {
4670        ranges.push(prev_chunk_trailing_whitespace_range);
4671    }
4672
4673    ranges
4674}