buffer.rs

   1pub use crate::{
   2    diagnostic_set::DiagnosticSet,
   3    highlight_map::{HighlightId, HighlightMap},
   4    proto, Grammar, Language, LanguageRegistry,
   5};
   6use crate::{
   7    diagnostic_set::{DiagnosticEntry, DiagnosticGroup},
   8    language_settings::{language_settings, LanguageSettings},
   9    outline::OutlineItem,
  10    syntax_map::{
  11        SyntaxLayer, SyntaxMap, SyntaxMapCapture, SyntaxMapCaptures, SyntaxMapMatch,
  12        SyntaxMapMatches, SyntaxSnapshot, ToTreeSitterPoint,
  13    },
  14    task_context::RunnableRange,
  15    text_diff::text_diff,
  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 smallvec::SmallVec;
  37use smol::future::yield_now;
  38use std::{
  39    any::Any,
  40    borrow::Cow,
  41    cell::Cell,
  42    cmp::{self, Ordering, Reverse},
  43    collections::{BTreeMap, BTreeSet},
  44    ffi::OsStr,
  45    fmt,
  46    future::Future,
  47    iter::{self, Iterator, Peekable},
  48    mem,
  49    num::NonZeroU32,
  50    ops::{Deref, DerefMut, Range},
  51    path::{Path, PathBuf},
  52    rc, str,
  53    sync::{Arc, LazyLock},
  54    time::{Duration, Instant},
  55    vec,
  56};
  57use sum_tree::TreeMap;
  58use text::operation_queue::OperationQueue;
  59use text::*;
  60pub use text::{
  61    Anchor, Bias, Buffer as TextBuffer, BufferId, BufferSnapshot as TextBufferSnapshot, Edit,
  62    OffsetRangeExt, OffsetUtf16, Patch, Point, PointUtf16, Rope, Selection, SelectionGoal,
  63    Subscription, TextDimension, TextSummary, ToOffset, ToOffsetUtf16, ToPoint, ToPointUtf16,
  64    Transaction, TransactionId, Unclipped,
  65};
  66use theme::{ActiveTheme as _, SyntaxTheme};
  67#[cfg(any(test, feature = "test-support"))]
  68use util::RandomCharIter;
  69use util::{debug_panic, maybe, RangeExt};
  70
  71#[cfg(any(test, feature = "test-support"))]
  72pub use {tree_sitter_rust, tree_sitter_typescript};
  73
  74pub use lsp::DiagnosticSeverity;
  75
  76/// A label for the background task spawned by the buffer to compute
  77/// a diff against the contents of its file.
  78pub static BUFFER_DIFF_TASK: LazyLock<TaskLabel> = LazyLock::new(TaskLabel::new);
  79
  80/// Indicate whether a [`Buffer`] has permissions to edit.
  81#[derive(PartialEq, Clone, Copy, Debug)]
  82pub enum Capability {
  83    /// The buffer is a mutable replica.
  84    ReadWrite,
  85    /// The buffer is a read-only replica.
  86    ReadOnly,
  87}
  88
  89pub type BufferRow = u32;
  90
  91/// An in-memory representation of a source code file, including its text,
  92/// syntax trees, git status, and diagnostics.
  93pub struct Buffer {
  94    text: TextBuffer,
  95    branch_state: Option<BufferBranchState>,
  96    /// Filesystem state, `None` when there is no path.
  97    file: Option<Arc<dyn File>>,
  98    /// The mtime of the file when this buffer was last loaded from
  99    /// or saved to disk.
 100    saved_mtime: Option<MTime>,
 101    /// The version vector when this buffer was last loaded from
 102    /// or saved to disk.
 103    saved_version: clock::Global,
 104    preview_version: clock::Global,
 105    transaction_depth: usize,
 106    was_dirty_before_starting_transaction: Option<bool>,
 107    reload_task: Option<Task<Result<()>>>,
 108    language: Option<Arc<Language>>,
 109    autoindent_requests: Vec<Arc<AutoindentRequest>>,
 110    pending_autoindent: Option<Task<()>>,
 111    sync_parse_timeout: Duration,
 112    syntax_map: Mutex<SyntaxMap>,
 113    parsing_in_background: bool,
 114    parse_status: (watch::Sender<ParseStatus>, watch::Receiver<ParseStatus>),
 115    non_text_state_update_count: usize,
 116    diagnostics: SmallVec<[(LanguageServerId, DiagnosticSet); 2]>,
 117    remote_selections: TreeMap<ReplicaId, SelectionSet>,
 118    diagnostics_timestamp: clock::Lamport,
 119    completion_triggers: BTreeSet<String>,
 120    completion_triggers_per_language_server: HashMap<LanguageServerId, BTreeSet<String>>,
 121    completion_triggers_timestamp: clock::Lamport,
 122    deferred_ops: OperationQueue<Operation>,
 123    capability: Capability,
 124    has_conflict: bool,
 125    /// Memoize calls to has_changes_since(saved_version).
 126    /// The contents of a cell are (self.version, has_changes) at the time of a last call.
 127    has_unsaved_edits: Cell<(clock::Global, bool)>,
 128    change_bits: Vec<rc::Weak<Cell<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    pub fn exists(&self) -> bool {
 374        match self {
 375            DiskState::New => false,
 376            DiskState::Present { .. } => true,
 377            DiskState::Deleted => false,
 378        }
 379    }
 380}
 381
 382/// The file associated with a buffer, in the case where the file is on the local disk.
 383pub trait LocalFile: File {
 384    /// Returns the absolute path of this file
 385    fn abs_path(&self, cx: &App) -> PathBuf;
 386
 387    /// Loads the file contents from disk and returns them as a UTF-8 encoded string.
 388    fn load(&self, cx: &App) -> Task<Result<String>>;
 389
 390    /// Loads the file's contents from disk.
 391    fn load_bytes(&self, cx: &App) -> Task<Result<Vec<u8>>>;
 392}
 393
 394/// The auto-indent behavior associated with an editing operation.
 395/// For some editing operations, each affected line of text has its
 396/// indentation recomputed. For other operations, the entire block
 397/// of edited text is adjusted uniformly.
 398#[derive(Clone, Debug)]
 399pub enum AutoindentMode {
 400    /// Indent each line of inserted text.
 401    EachLine,
 402    /// Apply the same indentation adjustment to all of the lines
 403    /// in a given insertion.
 404    Block {
 405        /// The original start column of each insertion, if it was
 406        /// copied from elsewhere.
 407        ///
 408        /// Knowing this start column makes it possible to preserve the
 409        /// relative indentation of every line in the insertion from
 410        /// when it was copied.
 411        ///
 412        /// If the start column is `a`, and the first line of insertion
 413        /// is then auto-indented to column `b`, then every other line of
 414        /// the insertion will be auto-indented to column `b - a`
 415        original_start_columns: Vec<u32>,
 416    },
 417}
 418
 419#[derive(Clone)]
 420struct AutoindentRequest {
 421    before_edit: BufferSnapshot,
 422    entries: Vec<AutoindentRequestEntry>,
 423    is_block_mode: bool,
 424    ignore_empty_lines: bool,
 425}
 426
 427#[derive(Debug, Clone)]
 428struct AutoindentRequestEntry {
 429    /// A range of the buffer whose indentation should be adjusted.
 430    range: Range<Anchor>,
 431    /// Whether or not these lines should be considered brand new, for the
 432    /// purpose of auto-indent. When text is not new, its indentation will
 433    /// only be adjusted if the suggested indentation level has *changed*
 434    /// since the edit was made.
 435    first_line_is_new: bool,
 436    indent_size: IndentSize,
 437    original_indent_column: Option<u32>,
 438}
 439
 440#[derive(Debug)]
 441struct IndentSuggestion {
 442    basis_row: u32,
 443    delta: Ordering,
 444    within_error: bool,
 445}
 446
 447struct BufferChunkHighlights<'a> {
 448    captures: SyntaxMapCaptures<'a>,
 449    next_capture: Option<SyntaxMapCapture<'a>>,
 450    stack: Vec<(usize, HighlightId)>,
 451    highlight_maps: Vec<HighlightMap>,
 452}
 453
 454/// An iterator that yields chunks of a buffer's text, along with their
 455/// syntax highlights and diagnostic status.
 456pub struct BufferChunks<'a> {
 457    buffer_snapshot: Option<&'a BufferSnapshot>,
 458    range: Range<usize>,
 459    chunks: text::Chunks<'a>,
 460    diagnostic_endpoints: Option<Peekable<vec::IntoIter<DiagnosticEndpoint>>>,
 461    error_depth: usize,
 462    warning_depth: usize,
 463    information_depth: usize,
 464    hint_depth: usize,
 465    unnecessary_depth: usize,
 466    highlights: Option<BufferChunkHighlights<'a>>,
 467}
 468
 469/// A chunk of a buffer's text, along with its syntax highlight and
 470/// diagnostic status.
 471#[derive(Clone, Debug, Default)]
 472pub struct Chunk<'a> {
 473    /// The text of the chunk.
 474    pub text: &'a str,
 475    /// The syntax highlighting style of the chunk.
 476    pub syntax_highlight_id: Option<HighlightId>,
 477    /// The highlight style that has been applied to this chunk in
 478    /// the editor.
 479    pub highlight_style: Option<HighlightStyle>,
 480    /// The severity of diagnostic associated with this chunk, if any.
 481    pub diagnostic_severity: Option<DiagnosticSeverity>,
 482    /// Whether this chunk of text is marked as unnecessary.
 483    pub is_unnecessary: bool,
 484    /// Whether this chunk of text was originally a tab character.
 485    pub is_tab: bool,
 486    /// An optional recipe for how the chunk should be presented.
 487    pub renderer: Option<ChunkRenderer>,
 488}
 489
 490/// A recipe for how the chunk should be presented.
 491#[derive(Clone)]
 492pub struct ChunkRenderer {
 493    /// creates a custom element to represent this chunk.
 494    pub render: Arc<dyn Send + Sync + Fn(&mut ChunkRendererContext) -> AnyElement>,
 495    /// If true, the element is constrained to the shaped width of the text.
 496    pub constrain_width: bool,
 497}
 498
 499pub struct ChunkRendererContext<'a, 'b> {
 500    pub window: &'a mut Window,
 501    pub context: &'b mut App,
 502    pub max_width: Pixels,
 503}
 504
 505impl fmt::Debug for ChunkRenderer {
 506    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 507        f.debug_struct("ChunkRenderer")
 508            .field("constrain_width", &self.constrain_width)
 509            .finish()
 510    }
 511}
 512
 513impl Deref for ChunkRendererContext<'_, '_> {
 514    type Target = App;
 515
 516    fn deref(&self) -> &Self::Target {
 517        self.context
 518    }
 519}
 520
 521impl DerefMut for ChunkRendererContext<'_, '_> {
 522    fn deref_mut(&mut self) -> &mut Self::Target {
 523        self.context
 524    }
 525}
 526
 527/// A set of edits to a given version of a buffer, computed asynchronously.
 528#[derive(Debug)]
 529pub struct Diff {
 530    pub(crate) base_version: clock::Global,
 531    line_ending: LineEnding,
 532    pub edits: Vec<(Range<usize>, Arc<str>)>,
 533}
 534
 535#[derive(Clone, Copy)]
 536pub(crate) struct DiagnosticEndpoint {
 537    offset: usize,
 538    is_start: bool,
 539    severity: DiagnosticSeverity,
 540    is_unnecessary: bool,
 541}
 542
 543/// A class of characters, used for characterizing a run of text.
 544#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug)]
 545pub enum CharKind {
 546    /// Whitespace.
 547    Whitespace,
 548    /// Punctuation.
 549    Punctuation,
 550    /// Word.
 551    Word,
 552}
 553
 554/// A runnable is a set of data about a region that could be resolved into a task
 555pub struct Runnable {
 556    pub tags: SmallVec<[RunnableTag; 1]>,
 557    pub language: Arc<Language>,
 558    pub buffer: BufferId,
 559}
 560
 561#[derive(Default, Clone, Debug)]
 562pub struct HighlightedText {
 563    pub text: SharedString,
 564    pub highlights: Vec<(Range<usize>, HighlightStyle)>,
 565}
 566
 567#[derive(Default, Debug)]
 568struct HighlightedTextBuilder {
 569    pub text: String,
 570    pub highlights: Vec<(Range<usize>, HighlightStyle)>,
 571}
 572
 573impl HighlightedText {
 574    pub fn from_buffer_range<T: ToOffset>(
 575        range: Range<T>,
 576        snapshot: &text::BufferSnapshot,
 577        syntax_snapshot: &SyntaxSnapshot,
 578        override_style: Option<HighlightStyle>,
 579        syntax_theme: &SyntaxTheme,
 580    ) -> Self {
 581        let mut highlighted_text = HighlightedTextBuilder::default();
 582        highlighted_text.add_text_from_buffer_range(
 583            range,
 584            snapshot,
 585            syntax_snapshot,
 586            override_style,
 587            syntax_theme,
 588        );
 589        highlighted_text.build()
 590    }
 591
 592    pub fn to_styled_text(&self, default_style: &TextStyle) -> StyledText {
 593        gpui::StyledText::new(self.text.clone())
 594            .with_default_highlights(default_style, self.highlights.iter().cloned())
 595    }
 596
 597    /// Returns the first line without leading whitespace unless highlighted
 598    /// and a boolean indicating if there are more lines after
 599    pub fn first_line_preview(self) -> (Self, bool) {
 600        let newline_ix = self.text.find('\n').unwrap_or(self.text.len());
 601        let first_line = &self.text[..newline_ix];
 602
 603        // Trim leading whitespace, unless an edit starts prior to it.
 604        let mut preview_start_ix = first_line.len() - first_line.trim_start().len();
 605        if let Some((first_highlight_range, _)) = self.highlights.first() {
 606            preview_start_ix = preview_start_ix.min(first_highlight_range.start);
 607        }
 608
 609        let preview_text = &first_line[preview_start_ix..];
 610        let preview_highlights = self
 611            .highlights
 612            .into_iter()
 613            .take_while(|(range, _)| range.start < newline_ix)
 614            .filter_map(|(mut range, highlight)| {
 615                range.start = range.start.saturating_sub(preview_start_ix);
 616                range.end = range.end.saturating_sub(preview_start_ix).min(newline_ix);
 617                if range.is_empty() {
 618                    None
 619                } else {
 620                    Some((range, highlight))
 621                }
 622            });
 623
 624        let preview = Self {
 625            text: SharedString::new(preview_text),
 626            highlights: preview_highlights.collect(),
 627        };
 628
 629        (preview, self.text.len() > newline_ix)
 630    }
 631}
 632
 633impl HighlightedTextBuilder {
 634    pub fn build(self) -> HighlightedText {
 635        HighlightedText {
 636            text: self.text.into(),
 637            highlights: self.highlights,
 638        }
 639    }
 640
 641    pub fn add_text_from_buffer_range<T: ToOffset>(
 642        &mut self,
 643        range: Range<T>,
 644        snapshot: &text::BufferSnapshot,
 645        syntax_snapshot: &SyntaxSnapshot,
 646        override_style: Option<HighlightStyle>,
 647        syntax_theme: &SyntaxTheme,
 648    ) {
 649        let range = range.to_offset(snapshot);
 650        for chunk in Self::highlighted_chunks(range, snapshot, syntax_snapshot) {
 651            let start = self.text.len();
 652            self.text.push_str(chunk.text);
 653            let end = self.text.len();
 654
 655            if let Some(mut highlight_style) = chunk
 656                .syntax_highlight_id
 657                .and_then(|id| id.style(syntax_theme))
 658            {
 659                if let Some(override_style) = override_style {
 660                    highlight_style.highlight(override_style);
 661                }
 662                self.highlights.push((start..end, highlight_style));
 663            } else if let Some(override_style) = override_style {
 664                self.highlights.push((start..end, override_style));
 665            }
 666        }
 667    }
 668
 669    fn highlighted_chunks<'a>(
 670        range: Range<usize>,
 671        snapshot: &'a text::BufferSnapshot,
 672        syntax_snapshot: &'a SyntaxSnapshot,
 673    ) -> BufferChunks<'a> {
 674        let captures = syntax_snapshot.captures(range.clone(), snapshot, |grammar| {
 675            grammar.highlights_query.as_ref()
 676        });
 677
 678        let highlight_maps = captures
 679            .grammars()
 680            .iter()
 681            .map(|grammar| grammar.highlight_map())
 682            .collect();
 683
 684        BufferChunks::new(
 685            snapshot.as_rope(),
 686            range,
 687            Some((captures, highlight_maps)),
 688            false,
 689            None,
 690        )
 691    }
 692}
 693
 694#[derive(Clone)]
 695pub struct EditPreview {
 696    old_snapshot: text::BufferSnapshot,
 697    applied_edits_snapshot: text::BufferSnapshot,
 698    syntax_snapshot: SyntaxSnapshot,
 699}
 700
 701impl EditPreview {
 702    pub fn highlight_edits(
 703        &self,
 704        current_snapshot: &BufferSnapshot,
 705        edits: &[(Range<Anchor>, String)],
 706        include_deletions: bool,
 707        cx: &App,
 708    ) -> HighlightedText {
 709        let Some(visible_range_in_preview_snapshot) = self.compute_visible_range(edits) else {
 710            return HighlightedText::default();
 711        };
 712
 713        let mut highlighted_text = HighlightedTextBuilder::default();
 714
 715        let mut offset_in_preview_snapshot = visible_range_in_preview_snapshot.start;
 716
 717        let insertion_highlight_style = HighlightStyle {
 718            background_color: Some(cx.theme().status().created_background),
 719            ..Default::default()
 720        };
 721        let deletion_highlight_style = HighlightStyle {
 722            background_color: Some(cx.theme().status().deleted_background),
 723            ..Default::default()
 724        };
 725        let syntax_theme = cx.theme().syntax();
 726
 727        for (range, edit_text) in edits {
 728            let edit_new_end_in_preview_snapshot = range
 729                .end
 730                .bias_right(&self.old_snapshot)
 731                .to_offset(&self.applied_edits_snapshot);
 732            let edit_start_in_preview_snapshot = edit_new_end_in_preview_snapshot - edit_text.len();
 733
 734            let unchanged_range_in_preview_snapshot =
 735                offset_in_preview_snapshot..edit_start_in_preview_snapshot;
 736            if !unchanged_range_in_preview_snapshot.is_empty() {
 737                highlighted_text.add_text_from_buffer_range(
 738                    unchanged_range_in_preview_snapshot,
 739                    &self.applied_edits_snapshot,
 740                    &self.syntax_snapshot,
 741                    None,
 742                    &syntax_theme,
 743                );
 744            }
 745
 746            let range_in_current_snapshot = range.to_offset(current_snapshot);
 747            if include_deletions && !range_in_current_snapshot.is_empty() {
 748                highlighted_text.add_text_from_buffer_range(
 749                    range_in_current_snapshot,
 750                    &current_snapshot.text,
 751                    &current_snapshot.syntax,
 752                    Some(deletion_highlight_style),
 753                    &syntax_theme,
 754                );
 755            }
 756
 757            if !edit_text.is_empty() {
 758                highlighted_text.add_text_from_buffer_range(
 759                    edit_start_in_preview_snapshot..edit_new_end_in_preview_snapshot,
 760                    &self.applied_edits_snapshot,
 761                    &self.syntax_snapshot,
 762                    Some(insertion_highlight_style),
 763                    &syntax_theme,
 764                );
 765            }
 766
 767            offset_in_preview_snapshot = edit_new_end_in_preview_snapshot;
 768        }
 769
 770        highlighted_text.add_text_from_buffer_range(
 771            offset_in_preview_snapshot..visible_range_in_preview_snapshot.end,
 772            &self.applied_edits_snapshot,
 773            &self.syntax_snapshot,
 774            None,
 775            &syntax_theme,
 776        );
 777
 778        highlighted_text.build()
 779    }
 780
 781    fn compute_visible_range(&self, edits: &[(Range<Anchor>, String)]) -> Option<Range<usize>> {
 782        let (first, _) = edits.first()?;
 783        let (last, _) = edits.last()?;
 784
 785        let start = first
 786            .start
 787            .bias_left(&self.old_snapshot)
 788            .to_point(&self.applied_edits_snapshot);
 789        let end = last
 790            .end
 791            .bias_right(&self.old_snapshot)
 792            .to_point(&self.applied_edits_snapshot);
 793
 794        // Ensure that the first line of the first edit and the last line of the last edit are always fully visible
 795        let range = Point::new(start.row, 0)
 796            ..Point::new(end.row, self.applied_edits_snapshot.line_len(end.row));
 797
 798        Some(range.to_offset(&self.applied_edits_snapshot))
 799    }
 800}
 801
 802#[derive(Clone, Debug, PartialEq, Eq)]
 803pub struct BracketMatch {
 804    pub open_range: Range<usize>,
 805    pub close_range: Range<usize>,
 806    pub newline_only: bool,
 807}
 808
 809impl Buffer {
 810    /// Create a new buffer with the given base text.
 811    pub fn local<T: Into<String>>(base_text: T, cx: &Context<Self>) -> Self {
 812        Self::build(
 813            TextBuffer::new(0, cx.entity_id().as_non_zero_u64().into(), base_text.into()),
 814            None,
 815            Capability::ReadWrite,
 816        )
 817    }
 818
 819    /// Create a new buffer with the given base text that has proper line endings and other normalization applied.
 820    pub fn local_normalized(
 821        base_text_normalized: Rope,
 822        line_ending: LineEnding,
 823        cx: &Context<Self>,
 824    ) -> Self {
 825        Self::build(
 826            TextBuffer::new_normalized(
 827                0,
 828                cx.entity_id().as_non_zero_u64().into(),
 829                line_ending,
 830                base_text_normalized,
 831            ),
 832            None,
 833            Capability::ReadWrite,
 834        )
 835    }
 836
 837    /// Create a new buffer that is a replica of a remote buffer.
 838    pub fn remote(
 839        remote_id: BufferId,
 840        replica_id: ReplicaId,
 841        capability: Capability,
 842        base_text: impl Into<String>,
 843    ) -> Self {
 844        Self::build(
 845            TextBuffer::new(replica_id, remote_id, base_text.into()),
 846            None,
 847            capability,
 848        )
 849    }
 850
 851    /// Create a new buffer that is a replica of a remote buffer, populating its
 852    /// state from the given protobuf message.
 853    pub fn from_proto(
 854        replica_id: ReplicaId,
 855        capability: Capability,
 856        message: proto::BufferState,
 857        file: Option<Arc<dyn File>>,
 858    ) -> Result<Self> {
 859        let buffer_id = BufferId::new(message.id)
 860            .with_context(|| anyhow!("Could not deserialize buffer_id"))?;
 861        let buffer = TextBuffer::new(replica_id, buffer_id, message.base_text);
 862        let mut this = Self::build(buffer, file, capability);
 863        this.text.set_line_ending(proto::deserialize_line_ending(
 864            rpc::proto::LineEnding::from_i32(message.line_ending)
 865                .ok_or_else(|| anyhow!("missing line_ending"))?,
 866        ));
 867        this.saved_version = proto::deserialize_version(&message.saved_version);
 868        this.saved_mtime = message.saved_mtime.map(|time| time.into());
 869        Ok(this)
 870    }
 871
 872    /// Serialize the buffer's state to a protobuf message.
 873    pub fn to_proto(&self, cx: &App) -> proto::BufferState {
 874        proto::BufferState {
 875            id: self.remote_id().into(),
 876            file: self.file.as_ref().map(|f| f.to_proto(cx)),
 877            base_text: self.base_text().to_string(),
 878            line_ending: proto::serialize_line_ending(self.line_ending()) as i32,
 879            saved_version: proto::serialize_version(&self.saved_version),
 880            saved_mtime: self.saved_mtime.map(|time| time.into()),
 881        }
 882    }
 883
 884    /// Serialize as protobufs all of the changes to the buffer since the given version.
 885    pub fn serialize_ops(
 886        &self,
 887        since: Option<clock::Global>,
 888        cx: &App,
 889    ) -> Task<Vec<proto::Operation>> {
 890        let mut operations = Vec::new();
 891        operations.extend(self.deferred_ops.iter().map(proto::serialize_operation));
 892
 893        operations.extend(self.remote_selections.iter().map(|(_, set)| {
 894            proto::serialize_operation(&Operation::UpdateSelections {
 895                selections: set.selections.clone(),
 896                lamport_timestamp: set.lamport_timestamp,
 897                line_mode: set.line_mode,
 898                cursor_shape: set.cursor_shape,
 899            })
 900        }));
 901
 902        for (server_id, diagnostics) in &self.diagnostics {
 903            operations.push(proto::serialize_operation(&Operation::UpdateDiagnostics {
 904                lamport_timestamp: self.diagnostics_timestamp,
 905                server_id: *server_id,
 906                diagnostics: diagnostics.iter().cloned().collect(),
 907            }));
 908        }
 909
 910        for (server_id, completions) in &self.completion_triggers_per_language_server {
 911            operations.push(proto::serialize_operation(
 912                &Operation::UpdateCompletionTriggers {
 913                    triggers: completions.iter().cloned().collect(),
 914                    lamport_timestamp: self.completion_triggers_timestamp,
 915                    server_id: *server_id,
 916                },
 917            ));
 918        }
 919
 920        let text_operations = self.text.operations().clone();
 921        cx.background_spawn(async move {
 922            let since = since.unwrap_or_default();
 923            operations.extend(
 924                text_operations
 925                    .iter()
 926                    .filter(|(_, op)| !since.observed(op.timestamp()))
 927                    .map(|(_, op)| proto::serialize_operation(&Operation::Buffer(op.clone()))),
 928            );
 929            operations.sort_unstable_by_key(proto::lamport_timestamp_for_operation);
 930            operations
 931        })
 932    }
 933
 934    /// Assign a language to the buffer, returning the buffer.
 935    pub fn with_language(mut self, language: Arc<Language>, cx: &mut Context<Self>) -> Self {
 936        self.set_language(Some(language), cx);
 937        self
 938    }
 939
 940    /// Returns the [`Capability`] of this buffer.
 941    pub fn capability(&self) -> Capability {
 942        self.capability
 943    }
 944
 945    /// Whether this buffer can only be read.
 946    pub fn read_only(&self) -> bool {
 947        self.capability == Capability::ReadOnly
 948    }
 949
 950    /// Builds a [`Buffer`] with the given underlying [`TextBuffer`], diff base, [`File`] and [`Capability`].
 951    pub fn build(buffer: TextBuffer, file: Option<Arc<dyn File>>, capability: Capability) -> Self {
 952        let saved_mtime = file.as_ref().and_then(|file| file.disk_state().mtime());
 953        let snapshot = buffer.snapshot();
 954        let syntax_map = Mutex::new(SyntaxMap::new(&snapshot));
 955        Self {
 956            saved_mtime,
 957            saved_version: buffer.version(),
 958            preview_version: buffer.version(),
 959            reload_task: None,
 960            transaction_depth: 0,
 961            was_dirty_before_starting_transaction: None,
 962            has_unsaved_edits: Cell::new((buffer.version(), false)),
 963            text: buffer,
 964            branch_state: None,
 965            file,
 966            capability,
 967            syntax_map,
 968            parsing_in_background: false,
 969            non_text_state_update_count: 0,
 970            sync_parse_timeout: Duration::from_millis(1),
 971            parse_status: async_watch::channel(ParseStatus::Idle),
 972            autoindent_requests: Default::default(),
 973            pending_autoindent: Default::default(),
 974            language: None,
 975            remote_selections: Default::default(),
 976            diagnostics: Default::default(),
 977            diagnostics_timestamp: Default::default(),
 978            completion_triggers: Default::default(),
 979            completion_triggers_per_language_server: Default::default(),
 980            completion_triggers_timestamp: Default::default(),
 981            deferred_ops: OperationQueue::new(),
 982            has_conflict: false,
 983            change_bits: Default::default(),
 984            _subscriptions: Vec::new(),
 985        }
 986    }
 987
 988    pub fn build_snapshot(
 989        text: Rope,
 990        language: Option<Arc<Language>>,
 991        language_registry: Option<Arc<LanguageRegistry>>,
 992        cx: &mut App,
 993    ) -> impl Future<Output = BufferSnapshot> {
 994        let entity_id = cx.reserve_entity::<Self>().entity_id();
 995        let buffer_id = entity_id.as_non_zero_u64().into();
 996        async move {
 997            let text =
 998                TextBuffer::new_normalized(0, buffer_id, Default::default(), text).snapshot();
 999            let mut syntax = SyntaxMap::new(&text).snapshot();
1000            if let Some(language) = language.clone() {
1001                let text = text.clone();
1002                let language = language.clone();
1003                let language_registry = language_registry.clone();
1004                syntax.reparse(&text, language_registry, language);
1005            }
1006            BufferSnapshot {
1007                text,
1008                syntax,
1009                file: None,
1010                diagnostics: Default::default(),
1011                remote_selections: Default::default(),
1012                language,
1013                non_text_state_update_count: 0,
1014            }
1015        }
1016    }
1017
1018    pub fn build_empty_snapshot(cx: &mut App) -> BufferSnapshot {
1019        let entity_id = cx.reserve_entity::<Self>().entity_id();
1020        let buffer_id = entity_id.as_non_zero_u64().into();
1021        let text =
1022            TextBuffer::new_normalized(0, buffer_id, Default::default(), Rope::new()).snapshot();
1023        let syntax = SyntaxMap::new(&text).snapshot();
1024        BufferSnapshot {
1025            text,
1026            syntax,
1027            file: None,
1028            diagnostics: Default::default(),
1029            remote_selections: Default::default(),
1030            language: None,
1031            non_text_state_update_count: 0,
1032        }
1033    }
1034
1035    #[cfg(any(test, feature = "test-support"))]
1036    pub fn build_snapshot_sync(
1037        text: Rope,
1038        language: Option<Arc<Language>>,
1039        language_registry: Option<Arc<LanguageRegistry>>,
1040        cx: &mut App,
1041    ) -> BufferSnapshot {
1042        let entity_id = cx.reserve_entity::<Self>().entity_id();
1043        let buffer_id = entity_id.as_non_zero_u64().into();
1044        let text = TextBuffer::new_normalized(0, buffer_id, Default::default(), text).snapshot();
1045        let mut syntax = SyntaxMap::new(&text).snapshot();
1046        if let Some(language) = language.clone() {
1047            let text = text.clone();
1048            let language = language.clone();
1049            let language_registry = language_registry.clone();
1050            syntax.reparse(&text, language_registry, language);
1051        }
1052        BufferSnapshot {
1053            text,
1054            syntax,
1055            file: None,
1056            diagnostics: Default::default(),
1057            remote_selections: Default::default(),
1058            language,
1059            non_text_state_update_count: 0,
1060        }
1061    }
1062
1063    /// Retrieve a snapshot of the buffer's current state. This is computationally
1064    /// cheap, and allows reading from the buffer on a background thread.
1065    pub fn snapshot(&self) -> BufferSnapshot {
1066        let text = self.text.snapshot();
1067        let mut syntax_map = self.syntax_map.lock();
1068        syntax_map.interpolate(&text);
1069        let syntax = syntax_map.snapshot();
1070
1071        BufferSnapshot {
1072            text,
1073            syntax,
1074            file: self.file.clone(),
1075            remote_selections: self.remote_selections.clone(),
1076            diagnostics: self.diagnostics.clone(),
1077            language: self.language.clone(),
1078            non_text_state_update_count: self.non_text_state_update_count,
1079        }
1080    }
1081
1082    pub fn branch(&mut self, cx: &mut Context<Self>) -> Entity<Self> {
1083        let this = cx.entity();
1084        cx.new(|cx| {
1085            let mut branch = Self {
1086                branch_state: Some(BufferBranchState {
1087                    base_buffer: this.clone(),
1088                    merged_operations: Default::default(),
1089                }),
1090                language: self.language.clone(),
1091                has_conflict: self.has_conflict,
1092                has_unsaved_edits: Cell::new(self.has_unsaved_edits.get_mut().clone()),
1093                _subscriptions: vec![cx.subscribe(&this, Self::on_base_buffer_event)],
1094                ..Self::build(self.text.branch(), self.file.clone(), self.capability())
1095            };
1096            if let Some(language_registry) = self.language_registry() {
1097                branch.set_language_registry(language_registry);
1098            }
1099
1100            // Reparse the branch buffer so that we get syntax highlighting immediately.
1101            branch.reparse(cx);
1102
1103            branch
1104        })
1105    }
1106
1107    pub fn preview_edits(
1108        &self,
1109        edits: Arc<[(Range<Anchor>, String)]>,
1110        cx: &App,
1111    ) -> Task<EditPreview> {
1112        let registry = self.language_registry();
1113        let language = self.language().cloned();
1114        let old_snapshot = self.text.snapshot();
1115        let mut branch_buffer = self.text.branch();
1116        let mut syntax_snapshot = self.syntax_map.lock().snapshot();
1117        cx.background_spawn(async move {
1118            if !edits.is_empty() {
1119                if let Some(language) = language.clone() {
1120                    syntax_snapshot.reparse(&old_snapshot, registry.clone(), language);
1121                }
1122
1123                branch_buffer.edit(edits.iter().cloned());
1124                let snapshot = branch_buffer.snapshot();
1125                syntax_snapshot.interpolate(&snapshot);
1126
1127                if let Some(language) = language {
1128                    syntax_snapshot.reparse(&snapshot, registry, language);
1129                }
1130            }
1131            EditPreview {
1132                old_snapshot,
1133                applied_edits_snapshot: branch_buffer.snapshot(),
1134                syntax_snapshot,
1135            }
1136        })
1137    }
1138
1139    /// Applies all of the changes in this buffer that intersect any of the
1140    /// given `ranges` to its base buffer.
1141    ///
1142    /// If `ranges` is empty, then all changes will be applied. This buffer must
1143    /// be a branch buffer to call this method.
1144    pub fn merge_into_base(&mut self, ranges: Vec<Range<usize>>, cx: &mut Context<Self>) {
1145        let Some(base_buffer) = self.base_buffer() else {
1146            debug_panic!("not a branch buffer");
1147            return;
1148        };
1149
1150        let mut ranges = if ranges.is_empty() {
1151            &[0..usize::MAX]
1152        } else {
1153            ranges.as_slice()
1154        }
1155        .into_iter()
1156        .peekable();
1157
1158        let mut edits = Vec::new();
1159        for edit in self.edits_since::<usize>(&base_buffer.read(cx).version()) {
1160            let mut is_included = false;
1161            while let Some(range) = ranges.peek() {
1162                if range.end < edit.new.start {
1163                    ranges.next().unwrap();
1164                } else {
1165                    if range.start <= edit.new.end {
1166                        is_included = true;
1167                    }
1168                    break;
1169                }
1170            }
1171
1172            if is_included {
1173                edits.push((
1174                    edit.old.clone(),
1175                    self.text_for_range(edit.new.clone()).collect::<String>(),
1176                ));
1177            }
1178        }
1179
1180        let operation = base_buffer.update(cx, |base_buffer, cx| {
1181            // cx.emit(BufferEvent::DiffBaseChanged);
1182            base_buffer.edit(edits, None, cx)
1183        });
1184
1185        if let Some(operation) = operation {
1186            if let Some(BufferBranchState {
1187                merged_operations, ..
1188            }) = &mut self.branch_state
1189            {
1190                merged_operations.push(operation);
1191            }
1192        }
1193    }
1194
1195    fn on_base_buffer_event(
1196        &mut self,
1197        _: Entity<Buffer>,
1198        event: &BufferEvent,
1199        cx: &mut Context<Self>,
1200    ) {
1201        let BufferEvent::Operation { operation, .. } = event else {
1202            return;
1203        };
1204        let Some(BufferBranchState {
1205            merged_operations, ..
1206        }) = &mut self.branch_state
1207        else {
1208            return;
1209        };
1210
1211        let mut operation_to_undo = None;
1212        if let Operation::Buffer(text::Operation::Edit(operation)) = &operation {
1213            if let Ok(ix) = merged_operations.binary_search(&operation.timestamp) {
1214                merged_operations.remove(ix);
1215                operation_to_undo = Some(operation.timestamp);
1216            }
1217        }
1218
1219        self.apply_ops([operation.clone()], cx);
1220
1221        if let Some(timestamp) = operation_to_undo {
1222            let counts = [(timestamp, u32::MAX)].into_iter().collect();
1223            self.undo_operations(counts, cx);
1224        }
1225    }
1226
1227    #[cfg(test)]
1228    pub(crate) fn as_text_snapshot(&self) -> &text::BufferSnapshot {
1229        &self.text
1230    }
1231
1232    /// Retrieve a snapshot of the buffer's raw text, without any
1233    /// language-related state like the syntax tree or diagnostics.
1234    pub fn text_snapshot(&self) -> text::BufferSnapshot {
1235        self.text.snapshot()
1236    }
1237
1238    /// The file associated with the buffer, if any.
1239    pub fn file(&self) -> Option<&Arc<dyn File>> {
1240        self.file.as_ref()
1241    }
1242
1243    /// The version of the buffer that was last saved or reloaded from disk.
1244    pub fn saved_version(&self) -> &clock::Global {
1245        &self.saved_version
1246    }
1247
1248    /// The mtime of the buffer's file when the buffer was last saved or reloaded from disk.
1249    pub fn saved_mtime(&self) -> Option<MTime> {
1250        self.saved_mtime
1251    }
1252
1253    /// Assign a language to the buffer.
1254    pub fn set_language(&mut self, language: Option<Arc<Language>>, cx: &mut Context<Self>) {
1255        self.non_text_state_update_count += 1;
1256        self.syntax_map.lock().clear(&self.text);
1257        self.language = language;
1258        self.was_changed();
1259        self.reparse(cx);
1260        cx.emit(BufferEvent::LanguageChanged);
1261    }
1262
1263    /// Assign a language registry to the buffer. This allows the buffer to retrieve
1264    /// other languages if parts of the buffer are written in different languages.
1265    pub fn set_language_registry(&self, language_registry: Arc<LanguageRegistry>) {
1266        self.syntax_map
1267            .lock()
1268            .set_language_registry(language_registry);
1269    }
1270
1271    pub fn language_registry(&self) -> Option<Arc<LanguageRegistry>> {
1272        self.syntax_map.lock().language_registry()
1273    }
1274
1275    /// Assign the buffer a new [`Capability`].
1276    pub fn set_capability(&mut self, capability: Capability, cx: &mut Context<Self>) {
1277        self.capability = capability;
1278        cx.emit(BufferEvent::CapabilityChanged)
1279    }
1280
1281    /// This method is called to signal that the buffer has been saved.
1282    pub fn did_save(
1283        &mut self,
1284        version: clock::Global,
1285        mtime: Option<MTime>,
1286        cx: &mut Context<Self>,
1287    ) {
1288        self.saved_version = version;
1289        self.has_unsaved_edits
1290            .set((self.saved_version().clone(), false));
1291        self.has_conflict = false;
1292        self.saved_mtime = mtime;
1293        self.was_changed();
1294        cx.emit(BufferEvent::Saved);
1295        cx.notify();
1296    }
1297
1298    /// This method is called to signal that the buffer has been discarded.
1299    pub fn discarded(&self, cx: &mut Context<Self>) {
1300        cx.emit(BufferEvent::Discarded);
1301        cx.notify();
1302    }
1303
1304    /// Reloads the contents of the buffer from disk.
1305    pub fn reload(&mut self, cx: &Context<Self>) -> oneshot::Receiver<Option<Transaction>> {
1306        let (tx, rx) = futures::channel::oneshot::channel();
1307        let prev_version = self.text.version();
1308        self.reload_task = Some(cx.spawn(|this, mut cx| async move {
1309            let Some((new_mtime, new_text)) = this.update(&mut cx, |this, cx| {
1310                let file = this.file.as_ref()?.as_local()?;
1311                Some((file.disk_state().mtime(), file.load(cx)))
1312            })?
1313            else {
1314                return Ok(());
1315            };
1316
1317            let new_text = new_text.await?;
1318            let diff = this
1319                .update(&mut cx, |this, cx| this.diff(new_text.clone(), cx))?
1320                .await;
1321            this.update(&mut cx, |this, cx| {
1322                if this.version() == diff.base_version {
1323                    this.finalize_last_transaction();
1324                    this.apply_diff(diff, cx);
1325                    tx.send(this.finalize_last_transaction().cloned()).ok();
1326                    this.has_conflict = false;
1327                    this.did_reload(this.version(), this.line_ending(), new_mtime, cx);
1328                } else {
1329                    if !diff.edits.is_empty()
1330                        || this
1331                            .edits_since::<usize>(&diff.base_version)
1332                            .next()
1333                            .is_some()
1334                    {
1335                        this.has_conflict = true;
1336                    }
1337
1338                    this.did_reload(prev_version, this.line_ending(), this.saved_mtime, cx);
1339                }
1340
1341                this.reload_task.take();
1342            })
1343        }));
1344        rx
1345    }
1346
1347    /// This method is called to signal that the buffer has been reloaded.
1348    pub fn did_reload(
1349        &mut self,
1350        version: clock::Global,
1351        line_ending: LineEnding,
1352        mtime: Option<MTime>,
1353        cx: &mut Context<Self>,
1354    ) {
1355        self.saved_version = version;
1356        self.has_unsaved_edits
1357            .set((self.saved_version.clone(), false));
1358        self.text.set_line_ending(line_ending);
1359        self.saved_mtime = mtime;
1360        cx.emit(BufferEvent::Reloaded);
1361        cx.notify();
1362    }
1363
1364    /// Updates the [`File`] backing this buffer. This should be called when
1365    /// the file has changed or has been deleted.
1366    pub fn file_updated(&mut self, new_file: Arc<dyn File>, cx: &mut Context<Self>) {
1367        let was_dirty = self.is_dirty();
1368        let mut file_changed = false;
1369
1370        if let Some(old_file) = self.file.as_ref() {
1371            if new_file.path() != old_file.path() {
1372                file_changed = true;
1373            }
1374
1375            let old_state = old_file.disk_state();
1376            let new_state = new_file.disk_state();
1377            if old_state != new_state {
1378                file_changed = true;
1379                if !was_dirty && matches!(new_state, DiskState::Present { .. }) {
1380                    cx.emit(BufferEvent::ReloadNeeded)
1381                }
1382            }
1383        } else {
1384            file_changed = true;
1385        };
1386
1387        self.file = Some(new_file);
1388        if file_changed {
1389            self.was_changed();
1390            self.non_text_state_update_count += 1;
1391            if was_dirty != self.is_dirty() {
1392                cx.emit(BufferEvent::DirtyChanged);
1393            }
1394            cx.emit(BufferEvent::FileHandleChanged);
1395            cx.notify();
1396        }
1397    }
1398
1399    pub fn base_buffer(&self) -> Option<Entity<Self>> {
1400        Some(self.branch_state.as_ref()?.base_buffer.clone())
1401    }
1402
1403    /// Returns the primary [`Language`] assigned to this [`Buffer`].
1404    pub fn language(&self) -> Option<&Arc<Language>> {
1405        self.language.as_ref()
1406    }
1407
1408    /// Returns the [`Language`] at the given location.
1409    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<Arc<Language>> {
1410        let offset = position.to_offset(self);
1411        self.syntax_map
1412            .lock()
1413            .layers_for_range(offset..offset, &self.text, false)
1414            .last()
1415            .map(|info| info.language.clone())
1416            .or_else(|| self.language.clone())
1417    }
1418
1419    /// An integer version number that accounts for all updates besides
1420    /// the buffer's text itself (which is versioned via a version vector).
1421    pub fn non_text_state_update_count(&self) -> usize {
1422        self.non_text_state_update_count
1423    }
1424
1425    /// Whether the buffer is being parsed in the background.
1426    #[cfg(any(test, feature = "test-support"))]
1427    pub fn is_parsing(&self) -> bool {
1428        self.parsing_in_background
1429    }
1430
1431    /// Indicates whether the buffer contains any regions that may be
1432    /// written in a language that hasn't been loaded yet.
1433    pub fn contains_unknown_injections(&self) -> bool {
1434        self.syntax_map.lock().contains_unknown_injections()
1435    }
1436
1437    #[cfg(test)]
1438    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
1439        self.sync_parse_timeout = timeout;
1440    }
1441
1442    /// Called after an edit to synchronize the buffer's main parse tree with
1443    /// the buffer's new underlying state.
1444    ///
1445    /// Locks the syntax map and interpolates the edits since the last reparse
1446    /// into the foreground syntax tree.
1447    ///
1448    /// Then takes a stable snapshot of the syntax map before unlocking it.
1449    /// The snapshot with the interpolated edits is sent to a background thread,
1450    /// where we ask Tree-sitter to perform an incremental parse.
1451    ///
1452    /// Meanwhile, in the foreground, we block the main thread for up to 1ms
1453    /// waiting on the parse to complete. As soon as it completes, we proceed
1454    /// synchronously, unless a 1ms timeout elapses.
1455    ///
1456    /// If we time out waiting on the parse, we spawn a second task waiting
1457    /// until the parse does complete and return with the interpolated tree still
1458    /// in the foreground. When the background parse completes, call back into
1459    /// the main thread and assign the foreground parse state.
1460    ///
1461    /// If the buffer or grammar changed since the start of the background parse,
1462    /// initiate an additional reparse recursively. To avoid concurrent parses
1463    /// for the same buffer, we only initiate a new parse if we are not already
1464    /// parsing in the background.
1465    pub fn reparse(&mut self, cx: &mut Context<Self>) {
1466        if self.parsing_in_background {
1467            return;
1468        }
1469        let language = if let Some(language) = self.language.clone() {
1470            language
1471        } else {
1472            return;
1473        };
1474
1475        let text = self.text_snapshot();
1476        let parsed_version = self.version();
1477
1478        let mut syntax_map = self.syntax_map.lock();
1479        syntax_map.interpolate(&text);
1480        let language_registry = syntax_map.language_registry();
1481        let mut syntax_snapshot = syntax_map.snapshot();
1482        drop(syntax_map);
1483
1484        let parse_task = cx.background_spawn({
1485            let language = language.clone();
1486            let language_registry = language_registry.clone();
1487            async move {
1488                syntax_snapshot.reparse(&text, language_registry, language);
1489                syntax_snapshot
1490            }
1491        });
1492
1493        self.parse_status.0.send(ParseStatus::Parsing).unwrap();
1494        match cx
1495            .background_executor()
1496            .block_with_timeout(self.sync_parse_timeout, parse_task)
1497        {
1498            Ok(new_syntax_snapshot) => {
1499                self.did_finish_parsing(new_syntax_snapshot, cx);
1500            }
1501            Err(parse_task) => {
1502                self.parsing_in_background = true;
1503                cx.spawn(move |this, mut cx| async move {
1504                    let new_syntax_map = parse_task.await;
1505                    this.update(&mut cx, move |this, cx| {
1506                        let grammar_changed =
1507                            this.language.as_ref().map_or(true, |current_language| {
1508                                !Arc::ptr_eq(&language, current_language)
1509                            });
1510                        let language_registry_changed = new_syntax_map
1511                            .contains_unknown_injections()
1512                            && language_registry.map_or(false, |registry| {
1513                                registry.version() != new_syntax_map.language_registry_version()
1514                            });
1515                        let parse_again = language_registry_changed
1516                            || grammar_changed
1517                            || this.version.changed_since(&parsed_version);
1518                        this.did_finish_parsing(new_syntax_map, cx);
1519                        this.parsing_in_background = false;
1520                        if parse_again {
1521                            this.reparse(cx);
1522                        }
1523                    })
1524                    .ok();
1525                })
1526                .detach();
1527            }
1528        }
1529    }
1530
1531    fn did_finish_parsing(&mut self, syntax_snapshot: SyntaxSnapshot, cx: &mut Context<Self>) {
1532        self.was_changed();
1533        self.non_text_state_update_count += 1;
1534        self.syntax_map.lock().did_parse(syntax_snapshot);
1535        self.request_autoindent(cx);
1536        self.parse_status.0.send(ParseStatus::Idle).unwrap();
1537        cx.emit(BufferEvent::Reparsed);
1538        cx.notify();
1539    }
1540
1541    pub fn parse_status(&self) -> watch::Receiver<ParseStatus> {
1542        self.parse_status.1.clone()
1543    }
1544
1545    /// Assign to the buffer a set of diagnostics created by a given language server.
1546    pub fn update_diagnostics(
1547        &mut self,
1548        server_id: LanguageServerId,
1549        diagnostics: DiagnosticSet,
1550        cx: &mut Context<Self>,
1551    ) {
1552        let lamport_timestamp = self.text.lamport_clock.tick();
1553        let op = Operation::UpdateDiagnostics {
1554            server_id,
1555            diagnostics: diagnostics.iter().cloned().collect(),
1556            lamport_timestamp,
1557        };
1558        self.apply_diagnostic_update(server_id, diagnostics, lamport_timestamp, cx);
1559        self.send_operation(op, true, cx);
1560    }
1561
1562    fn request_autoindent(&mut self, cx: &mut Context<Self>) {
1563        if let Some(indent_sizes) = self.compute_autoindents() {
1564            let indent_sizes = cx.background_spawn(indent_sizes);
1565            match cx
1566                .background_executor()
1567                .block_with_timeout(Duration::from_micros(500), indent_sizes)
1568            {
1569                Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
1570                Err(indent_sizes) => {
1571                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
1572                        let indent_sizes = indent_sizes.await;
1573                        this.update(&mut cx, |this, cx| {
1574                            this.apply_autoindents(indent_sizes, cx);
1575                        })
1576                        .ok();
1577                    }));
1578                }
1579            }
1580        } else {
1581            self.autoindent_requests.clear();
1582        }
1583    }
1584
1585    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>>> {
1586        let max_rows_between_yields = 100;
1587        let snapshot = self.snapshot();
1588        if snapshot.syntax.is_empty() || self.autoindent_requests.is_empty() {
1589            return None;
1590        }
1591
1592        let autoindent_requests = self.autoindent_requests.clone();
1593        Some(async move {
1594            let mut indent_sizes = BTreeMap::<u32, (IndentSize, bool)>::new();
1595            for request in autoindent_requests {
1596                // Resolve each edited range to its row in the current buffer and in the
1597                // buffer before this batch of edits.
1598                let mut row_ranges = Vec::new();
1599                let mut old_to_new_rows = BTreeMap::new();
1600                let mut language_indent_sizes_by_new_row = Vec::new();
1601                for entry in &request.entries {
1602                    let position = entry.range.start;
1603                    let new_row = position.to_point(&snapshot).row;
1604                    let new_end_row = entry.range.end.to_point(&snapshot).row + 1;
1605                    language_indent_sizes_by_new_row.push((new_row, entry.indent_size));
1606
1607                    if !entry.first_line_is_new {
1608                        let old_row = position.to_point(&request.before_edit).row;
1609                        old_to_new_rows.insert(old_row, new_row);
1610                    }
1611                    row_ranges.push((new_row..new_end_row, entry.original_indent_column));
1612                }
1613
1614                // Build a map containing the suggested indentation for each of the edited lines
1615                // with respect to the state of the buffer before these edits. This map is keyed
1616                // by the rows for these lines in the current state of the buffer.
1617                let mut old_suggestions = BTreeMap::<u32, (IndentSize, bool)>::default();
1618                let old_edited_ranges =
1619                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
1620                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1621                let mut language_indent_size = IndentSize::default();
1622                for old_edited_range in old_edited_ranges {
1623                    let suggestions = request
1624                        .before_edit
1625                        .suggest_autoindents(old_edited_range.clone())
1626                        .into_iter()
1627                        .flatten();
1628                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
1629                        if let Some(suggestion) = suggestion {
1630                            let new_row = *old_to_new_rows.get(&old_row).unwrap();
1631
1632                            // Find the indent size based on the language for this row.
1633                            while let Some((row, size)) = language_indent_sizes.peek() {
1634                                if *row > new_row {
1635                                    break;
1636                                }
1637                                language_indent_size = *size;
1638                                language_indent_sizes.next();
1639                            }
1640
1641                            let suggested_indent = old_to_new_rows
1642                                .get(&suggestion.basis_row)
1643                                .and_then(|from_row| {
1644                                    Some(old_suggestions.get(from_row).copied()?.0)
1645                                })
1646                                .unwrap_or_else(|| {
1647                                    request
1648                                        .before_edit
1649                                        .indent_size_for_line(suggestion.basis_row)
1650                                })
1651                                .with_delta(suggestion.delta, language_indent_size);
1652                            old_suggestions
1653                                .insert(new_row, (suggested_indent, suggestion.within_error));
1654                        }
1655                    }
1656                    yield_now().await;
1657                }
1658
1659                // Compute new suggestions for each line, but only include them in the result
1660                // if they differ from the old suggestion for that line.
1661                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1662                let mut language_indent_size = IndentSize::default();
1663                for (row_range, original_indent_column) in row_ranges {
1664                    let new_edited_row_range = if request.is_block_mode {
1665                        row_range.start..row_range.start + 1
1666                    } else {
1667                        row_range.clone()
1668                    };
1669
1670                    let suggestions = snapshot
1671                        .suggest_autoindents(new_edited_row_range.clone())
1672                        .into_iter()
1673                        .flatten();
1674                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
1675                        if let Some(suggestion) = suggestion {
1676                            // Find the indent size based on the language for this row.
1677                            while let Some((row, size)) = language_indent_sizes.peek() {
1678                                if *row > new_row {
1679                                    break;
1680                                }
1681                                language_indent_size = *size;
1682                                language_indent_sizes.next();
1683                            }
1684
1685                            let suggested_indent = indent_sizes
1686                                .get(&suggestion.basis_row)
1687                                .copied()
1688                                .map(|e| e.0)
1689                                .unwrap_or_else(|| {
1690                                    snapshot.indent_size_for_line(suggestion.basis_row)
1691                                })
1692                                .with_delta(suggestion.delta, language_indent_size);
1693
1694                            if old_suggestions.get(&new_row).map_or(
1695                                true,
1696                                |(old_indentation, was_within_error)| {
1697                                    suggested_indent != *old_indentation
1698                                        && (!suggestion.within_error || *was_within_error)
1699                                },
1700                            ) {
1701                                indent_sizes.insert(
1702                                    new_row,
1703                                    (suggested_indent, request.ignore_empty_lines),
1704                                );
1705                            }
1706                        }
1707                    }
1708
1709                    if let (true, Some(original_indent_column)) =
1710                        (request.is_block_mode, original_indent_column)
1711                    {
1712                        let new_indent =
1713                            if let Some((indent, _)) = indent_sizes.get(&row_range.start) {
1714                                *indent
1715                            } else {
1716                                snapshot.indent_size_for_line(row_range.start)
1717                            };
1718                        let delta = new_indent.len as i64 - original_indent_column as i64;
1719                        if delta != 0 {
1720                            for row in row_range.skip(1) {
1721                                indent_sizes.entry(row).or_insert_with(|| {
1722                                    let mut size = snapshot.indent_size_for_line(row);
1723                                    if size.kind == new_indent.kind {
1724                                        match delta.cmp(&0) {
1725                                            Ordering::Greater => size.len += delta as u32,
1726                                            Ordering::Less => {
1727                                                size.len = size.len.saturating_sub(-delta as u32)
1728                                            }
1729                                            Ordering::Equal => {}
1730                                        }
1731                                    }
1732                                    (size, request.ignore_empty_lines)
1733                                });
1734                            }
1735                        }
1736                    }
1737
1738                    yield_now().await;
1739                }
1740            }
1741
1742            indent_sizes
1743                .into_iter()
1744                .filter_map(|(row, (indent, ignore_empty_lines))| {
1745                    if ignore_empty_lines && snapshot.line_len(row) == 0 {
1746                        None
1747                    } else {
1748                        Some((row, indent))
1749                    }
1750                })
1751                .collect()
1752        })
1753    }
1754
1755    fn apply_autoindents(
1756        &mut self,
1757        indent_sizes: BTreeMap<u32, IndentSize>,
1758        cx: &mut Context<Self>,
1759    ) {
1760        self.autoindent_requests.clear();
1761
1762        let edits: Vec<_> = indent_sizes
1763            .into_iter()
1764            .filter_map(|(row, indent_size)| {
1765                let current_size = indent_size_for_line(self, row);
1766                Self::edit_for_indent_size_adjustment(row, current_size, indent_size)
1767            })
1768            .collect();
1769
1770        let preserve_preview = self.preserve_preview();
1771        self.edit(edits, None, cx);
1772        if preserve_preview {
1773            self.refresh_preview();
1774        }
1775    }
1776
1777    /// Create a minimal edit that will cause the given row to be indented
1778    /// with the given size. After applying this edit, the length of the line
1779    /// will always be at least `new_size.len`.
1780    pub fn edit_for_indent_size_adjustment(
1781        row: u32,
1782        current_size: IndentSize,
1783        new_size: IndentSize,
1784    ) -> Option<(Range<Point>, String)> {
1785        if new_size.kind == current_size.kind {
1786            match new_size.len.cmp(&current_size.len) {
1787                Ordering::Greater => {
1788                    let point = Point::new(row, 0);
1789                    Some((
1790                        point..point,
1791                        iter::repeat(new_size.char())
1792                            .take((new_size.len - current_size.len) as usize)
1793                            .collect::<String>(),
1794                    ))
1795                }
1796
1797                Ordering::Less => Some((
1798                    Point::new(row, 0)..Point::new(row, current_size.len - new_size.len),
1799                    String::new(),
1800                )),
1801
1802                Ordering::Equal => None,
1803            }
1804        } else {
1805            Some((
1806                Point::new(row, 0)..Point::new(row, current_size.len),
1807                iter::repeat(new_size.char())
1808                    .take(new_size.len as usize)
1809                    .collect::<String>(),
1810            ))
1811        }
1812    }
1813
1814    /// Spawns a background task that asynchronously computes a `Diff` between the buffer's text
1815    /// and the given new text.
1816    pub fn diff(&self, mut new_text: String, cx: &App) -> Task<Diff> {
1817        let old_text = self.as_rope().clone();
1818        let base_version = self.version();
1819        cx.background_executor()
1820            .spawn_labeled(*BUFFER_DIFF_TASK, async move {
1821                let old_text = old_text.to_string();
1822                let line_ending = LineEnding::detect(&new_text);
1823                LineEnding::normalize(&mut new_text);
1824                let edits = text_diff(&old_text, &new_text);
1825                Diff {
1826                    base_version,
1827                    line_ending,
1828                    edits,
1829                }
1830            })
1831    }
1832
1833    /// Spawns a background task that searches the buffer for any whitespace
1834    /// at the ends of a lines, and returns a `Diff` that removes that whitespace.
1835    pub fn remove_trailing_whitespace(&self, cx: &App) -> Task<Diff> {
1836        let old_text = self.as_rope().clone();
1837        let line_ending = self.line_ending();
1838        let base_version = self.version();
1839        cx.background_spawn(async move {
1840            let ranges = trailing_whitespace_ranges(&old_text);
1841            let empty = Arc::<str>::from("");
1842            Diff {
1843                base_version,
1844                line_ending,
1845                edits: ranges
1846                    .into_iter()
1847                    .map(|range| (range, empty.clone()))
1848                    .collect(),
1849            }
1850        })
1851    }
1852
1853    /// Ensures that the buffer ends with a single newline character, and
1854    /// no other whitespace.
1855    pub fn ensure_final_newline(&mut self, cx: &mut Context<Self>) {
1856        let len = self.len();
1857        let mut offset = len;
1858        for chunk in self.as_rope().reversed_chunks_in_range(0..len) {
1859            let non_whitespace_len = chunk
1860                .trim_end_matches(|c: char| c.is_ascii_whitespace())
1861                .len();
1862            offset -= chunk.len();
1863            offset += non_whitespace_len;
1864            if non_whitespace_len != 0 {
1865                if offset == len - 1 && chunk.get(non_whitespace_len..) == Some("\n") {
1866                    return;
1867                }
1868                break;
1869            }
1870        }
1871        self.edit([(offset..len, "\n")], None, cx);
1872    }
1873
1874    /// Applies a diff to the buffer. If the buffer has changed since the given diff was
1875    /// calculated, then adjust the diff to account for those changes, and discard any
1876    /// parts of the diff that conflict with those changes.
1877    pub fn apply_diff(&mut self, diff: Diff, cx: &mut Context<Self>) -> Option<TransactionId> {
1878        // Check for any edits to the buffer that have occurred since this diff
1879        // was computed.
1880        let snapshot = self.snapshot();
1881        let mut edits_since = snapshot.edits_since::<usize>(&diff.base_version).peekable();
1882        let mut delta = 0;
1883        let adjusted_edits = diff.edits.into_iter().filter_map(|(range, new_text)| {
1884            while let Some(edit_since) = edits_since.peek() {
1885                // If the edit occurs after a diff hunk, then it does not
1886                // affect that hunk.
1887                if edit_since.old.start > range.end {
1888                    break;
1889                }
1890                // If the edit precedes the diff hunk, then adjust the hunk
1891                // to reflect the edit.
1892                else if edit_since.old.end < range.start {
1893                    delta += edit_since.new_len() as i64 - edit_since.old_len() as i64;
1894                    edits_since.next();
1895                }
1896                // If the edit intersects a diff hunk, then discard that hunk.
1897                else {
1898                    return None;
1899                }
1900            }
1901
1902            let start = (range.start as i64 + delta) as usize;
1903            let end = (range.end as i64 + delta) as usize;
1904            Some((start..end, new_text))
1905        });
1906
1907        self.start_transaction();
1908        self.text.set_line_ending(diff.line_ending);
1909        self.edit(adjusted_edits, None, cx);
1910        self.end_transaction(cx)
1911    }
1912
1913    fn has_unsaved_edits(&self) -> bool {
1914        let (last_version, has_unsaved_edits) = self.has_unsaved_edits.take();
1915
1916        if last_version == self.version {
1917            self.has_unsaved_edits
1918                .set((last_version, has_unsaved_edits));
1919            return has_unsaved_edits;
1920        }
1921
1922        let has_edits = self.has_edits_since(&self.saved_version);
1923        self.has_unsaved_edits
1924            .set((self.version.clone(), has_edits));
1925        has_edits
1926    }
1927
1928    /// Checks if the buffer has unsaved changes.
1929    pub fn is_dirty(&self) -> bool {
1930        if self.capability == Capability::ReadOnly {
1931            return false;
1932        }
1933        if self.has_conflict || self.has_unsaved_edits() {
1934            return true;
1935        }
1936        match self.file.as_ref().map(|f| f.disk_state()) {
1937            Some(DiskState::New) => !self.is_empty(),
1938            Some(DiskState::Deleted) => true,
1939            _ => false,
1940        }
1941    }
1942
1943    /// Checks if the buffer and its file have both changed since the buffer
1944    /// was last saved or reloaded.
1945    pub fn has_conflict(&self) -> bool {
1946        if self.has_conflict {
1947            return true;
1948        }
1949        let Some(file) = self.file.as_ref() else {
1950            return false;
1951        };
1952        match file.disk_state() {
1953            DiskState::New => false,
1954            DiskState::Present { mtime } => match self.saved_mtime {
1955                Some(saved_mtime) => {
1956                    mtime.bad_is_greater_than(saved_mtime) && self.has_unsaved_edits()
1957                }
1958                None => true,
1959            },
1960            DiskState::Deleted => true,
1961        }
1962    }
1963
1964    /// Gets a [`Subscription`] that tracks all of the changes to the buffer's text.
1965    pub fn subscribe(&mut self) -> Subscription {
1966        self.text.subscribe()
1967    }
1968
1969    /// Adds a bit to the list of bits that are set when the buffer's text changes.
1970    ///
1971    /// This allows downstream code to check if the buffer's text has changed without
1972    /// waiting for an effect cycle, which would be required if using eents.
1973    pub fn record_changes(&mut self, bit: rc::Weak<Cell<bool>>) {
1974        if let Err(ix) = self
1975            .change_bits
1976            .binary_search_by_key(&rc::Weak::as_ptr(&bit), rc::Weak::as_ptr)
1977        {
1978            self.change_bits.insert(ix, bit);
1979        }
1980    }
1981
1982    fn was_changed(&mut self) {
1983        self.change_bits.retain(|change_bit| {
1984            change_bit.upgrade().map_or(false, |bit| {
1985                bit.replace(true);
1986                true
1987            })
1988        });
1989    }
1990
1991    /// Starts a transaction, if one is not already in-progress. When undoing or
1992    /// redoing edits, all of the edits performed within a transaction are undone
1993    /// or redone together.
1994    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1995        self.start_transaction_at(Instant::now())
1996    }
1997
1998    /// Starts a transaction, providing the current time. Subsequent transactions
1999    /// that occur within a short period of time will be grouped together. This
2000    /// is controlled by the buffer's undo grouping duration.
2001    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
2002        self.transaction_depth += 1;
2003        if self.was_dirty_before_starting_transaction.is_none() {
2004            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
2005        }
2006        self.text.start_transaction_at(now)
2007    }
2008
2009    /// Terminates the current transaction, if this is the outermost transaction.
2010    pub fn end_transaction(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2011        self.end_transaction_at(Instant::now(), cx)
2012    }
2013
2014    /// Terminates the current transaction, providing the current time. Subsequent transactions
2015    /// that occur within a short period of time will be grouped together. This
2016    /// is controlled by the buffer's undo grouping duration.
2017    pub fn end_transaction_at(
2018        &mut self,
2019        now: Instant,
2020        cx: &mut Context<Self>,
2021    ) -> Option<TransactionId> {
2022        assert!(self.transaction_depth > 0);
2023        self.transaction_depth -= 1;
2024        let was_dirty = if self.transaction_depth == 0 {
2025            self.was_dirty_before_starting_transaction.take().unwrap()
2026        } else {
2027            false
2028        };
2029        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
2030            self.did_edit(&start_version, was_dirty, cx);
2031            Some(transaction_id)
2032        } else {
2033            None
2034        }
2035    }
2036
2037    /// Manually add a transaction to the buffer's undo history.
2038    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
2039        self.text.push_transaction(transaction, now);
2040    }
2041
2042    /// Prevent the last transaction from being grouped with any subsequent transactions,
2043    /// even if they occur with the buffer's undo grouping duration.
2044    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
2045        self.text.finalize_last_transaction()
2046    }
2047
2048    /// Manually group all changes since a given transaction.
2049    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
2050        self.text.group_until_transaction(transaction_id);
2051    }
2052
2053    /// Manually remove a transaction from the buffer's undo history
2054    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
2055        self.text.forget_transaction(transaction_id);
2056    }
2057
2058    /// Manually merge two adjacent transactions in the buffer's undo history.
2059    pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
2060        self.text.merge_transactions(transaction, destination);
2061    }
2062
2063    /// Waits for the buffer to receive operations with the given timestamps.
2064    pub fn wait_for_edits(
2065        &mut self,
2066        edit_ids: impl IntoIterator<Item = clock::Lamport>,
2067    ) -> impl Future<Output = Result<()>> {
2068        self.text.wait_for_edits(edit_ids)
2069    }
2070
2071    /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
2072    pub fn wait_for_anchors(
2073        &mut self,
2074        anchors: impl IntoIterator<Item = Anchor>,
2075    ) -> impl 'static + Future<Output = Result<()>> {
2076        self.text.wait_for_anchors(anchors)
2077    }
2078
2079    /// Waits for the buffer to receive operations up to the given version.
2080    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
2081        self.text.wait_for_version(version)
2082    }
2083
2084    /// Forces all futures returned by [`Buffer::wait_for_version`], [`Buffer::wait_for_edits`], or
2085    /// [`Buffer::wait_for_version`] to resolve with an error.
2086    pub fn give_up_waiting(&mut self) {
2087        self.text.give_up_waiting();
2088    }
2089
2090    /// Stores a set of selections that should be broadcasted to all of the buffer's replicas.
2091    pub fn set_active_selections(
2092        &mut self,
2093        selections: Arc<[Selection<Anchor>]>,
2094        line_mode: bool,
2095        cursor_shape: CursorShape,
2096        cx: &mut Context<Self>,
2097    ) {
2098        let lamport_timestamp = self.text.lamport_clock.tick();
2099        self.remote_selections.insert(
2100            self.text.replica_id(),
2101            SelectionSet {
2102                selections: selections.clone(),
2103                lamport_timestamp,
2104                line_mode,
2105                cursor_shape,
2106            },
2107        );
2108        self.send_operation(
2109            Operation::UpdateSelections {
2110                selections,
2111                line_mode,
2112                lamport_timestamp,
2113                cursor_shape,
2114            },
2115            true,
2116            cx,
2117        );
2118        self.non_text_state_update_count += 1;
2119        cx.notify();
2120    }
2121
2122    /// Clears the selections, so that other replicas of the buffer do not see any selections for
2123    /// this replica.
2124    pub fn remove_active_selections(&mut self, cx: &mut Context<Self>) {
2125        if self
2126            .remote_selections
2127            .get(&self.text.replica_id())
2128            .map_or(true, |set| !set.selections.is_empty())
2129        {
2130            self.set_active_selections(Arc::default(), false, Default::default(), cx);
2131        }
2132    }
2133
2134    /// Replaces the buffer's entire text.
2135    pub fn set_text<T>(&mut self, text: T, cx: &mut Context<Self>) -> Option<clock::Lamport>
2136    where
2137        T: Into<Arc<str>>,
2138    {
2139        self.autoindent_requests.clear();
2140        self.edit([(0..self.len(), text)], None, cx)
2141    }
2142
2143    /// Applies the given edits to the buffer. Each edit is specified as a range of text to
2144    /// delete, and a string of text to insert at that location.
2145    ///
2146    /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
2147    /// request for the edited ranges, which will be processed when the buffer finishes
2148    /// parsing.
2149    ///
2150    /// Parsing takes place at the end of a transaction, and may compute synchronously
2151    /// or asynchronously, depending on the changes.
2152    pub fn edit<I, S, T>(
2153        &mut self,
2154        edits_iter: I,
2155        autoindent_mode: Option<AutoindentMode>,
2156        cx: &mut Context<Self>,
2157    ) -> Option<clock::Lamport>
2158    where
2159        I: IntoIterator<Item = (Range<S>, T)>,
2160        S: ToOffset,
2161        T: Into<Arc<str>>,
2162    {
2163        // Skip invalid edits and coalesce contiguous ones.
2164        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
2165        for (range, new_text) in edits_iter {
2166            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2167            if range.start > range.end {
2168                mem::swap(&mut range.start, &mut range.end);
2169            }
2170            let new_text = new_text.into();
2171            if !new_text.is_empty() || !range.is_empty() {
2172                if let Some((prev_range, prev_text)) = edits.last_mut() {
2173                    if prev_range.end >= range.start {
2174                        prev_range.end = cmp::max(prev_range.end, range.end);
2175                        *prev_text = format!("{prev_text}{new_text}").into();
2176                    } else {
2177                        edits.push((range, new_text));
2178                    }
2179                } else {
2180                    edits.push((range, new_text));
2181                }
2182            }
2183        }
2184        if edits.is_empty() {
2185            return None;
2186        }
2187
2188        self.start_transaction();
2189        self.pending_autoindent.take();
2190        let autoindent_request = autoindent_mode
2191            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
2192
2193        let edit_operation = self.text.edit(edits.iter().cloned());
2194        let edit_id = edit_operation.timestamp();
2195
2196        if let Some((before_edit, mode)) = autoindent_request {
2197            let mut delta = 0isize;
2198            let entries = edits
2199                .into_iter()
2200                .enumerate()
2201                .zip(&edit_operation.as_edit().unwrap().new_text)
2202                .map(|((ix, (range, _)), new_text)| {
2203                    let new_text_length = new_text.len();
2204                    let old_start = range.start.to_point(&before_edit);
2205                    let new_start = (delta + range.start as isize) as usize;
2206                    let range_len = range.end - range.start;
2207                    delta += new_text_length as isize - range_len as isize;
2208
2209                    // Decide what range of the insertion to auto-indent, and whether
2210                    // the first line of the insertion should be considered a newly-inserted line
2211                    // or an edit to an existing line.
2212                    let mut range_of_insertion_to_indent = 0..new_text_length;
2213                    let mut first_line_is_new = true;
2214
2215                    let old_line_start = before_edit.indent_size_for_line(old_start.row).len;
2216                    let old_line_end = before_edit.line_len(old_start.row);
2217
2218                    if old_start.column > old_line_start {
2219                        first_line_is_new = false;
2220                    }
2221
2222                    if !new_text.contains('\n')
2223                        && (old_start.column + (range_len as u32) < old_line_end
2224                            || old_line_end == old_line_start)
2225                    {
2226                        first_line_is_new = false;
2227                    }
2228
2229                    // When inserting text starting with a newline, avoid auto-indenting the
2230                    // previous line.
2231                    if new_text.starts_with('\n') {
2232                        range_of_insertion_to_indent.start += 1;
2233                        first_line_is_new = true;
2234                    }
2235
2236                    let mut original_indent_column = None;
2237                    if let AutoindentMode::Block {
2238                        original_start_columns,
2239                    } = &mode
2240                    {
2241                        original_indent_column = Some(
2242                            original_start_columns.get(ix).copied().unwrap_or(0)
2243                                + indent_size_for_text(
2244                                    new_text[range_of_insertion_to_indent.clone()].chars(),
2245                                )
2246                                .len,
2247                        );
2248
2249                        // Avoid auto-indenting the line after the edit.
2250                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
2251                            range_of_insertion_to_indent.end -= 1;
2252                        }
2253                    }
2254
2255                    AutoindentRequestEntry {
2256                        first_line_is_new,
2257                        original_indent_column,
2258                        indent_size: before_edit.language_indent_size_at(range.start, cx),
2259                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
2260                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
2261                    }
2262                })
2263                .collect();
2264
2265            self.autoindent_requests.push(Arc::new(AutoindentRequest {
2266                before_edit,
2267                entries,
2268                is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
2269                ignore_empty_lines: false,
2270            }));
2271        }
2272
2273        self.end_transaction(cx);
2274        self.send_operation(Operation::Buffer(edit_operation), true, cx);
2275        Some(edit_id)
2276    }
2277
2278    fn did_edit(&mut self, old_version: &clock::Global, was_dirty: bool, cx: &mut Context<Self>) {
2279        self.was_changed();
2280
2281        if self.edits_since::<usize>(old_version).next().is_none() {
2282            return;
2283        }
2284
2285        self.reparse(cx);
2286        cx.emit(BufferEvent::Edited);
2287        if was_dirty != self.is_dirty() {
2288            cx.emit(BufferEvent::DirtyChanged);
2289        }
2290        cx.notify();
2291    }
2292
2293    pub fn autoindent_ranges<I, T>(&mut self, ranges: I, cx: &mut Context<Self>)
2294    where
2295        I: IntoIterator<Item = Range<T>>,
2296        T: ToOffset + Copy,
2297    {
2298        let before_edit = self.snapshot();
2299        let entries = ranges
2300            .into_iter()
2301            .map(|range| AutoindentRequestEntry {
2302                range: before_edit.anchor_before(range.start)..before_edit.anchor_after(range.end),
2303                first_line_is_new: true,
2304                indent_size: before_edit.language_indent_size_at(range.start, cx),
2305                original_indent_column: None,
2306            })
2307            .collect();
2308        self.autoindent_requests.push(Arc::new(AutoindentRequest {
2309            before_edit,
2310            entries,
2311            is_block_mode: false,
2312            ignore_empty_lines: true,
2313        }));
2314        self.request_autoindent(cx);
2315    }
2316
2317    // Inserts newlines at the given position to create an empty line, returning the start of the new line.
2318    // You can also request the insertion of empty lines above and below the line starting at the returned point.
2319    pub fn insert_empty_line(
2320        &mut self,
2321        position: impl ToPoint,
2322        space_above: bool,
2323        space_below: bool,
2324        cx: &mut Context<Self>,
2325    ) -> Point {
2326        let mut position = position.to_point(self);
2327
2328        self.start_transaction();
2329
2330        self.edit(
2331            [(position..position, "\n")],
2332            Some(AutoindentMode::EachLine),
2333            cx,
2334        );
2335
2336        if position.column > 0 {
2337            position += Point::new(1, 0);
2338        }
2339
2340        if !self.is_line_blank(position.row) {
2341            self.edit(
2342                [(position..position, "\n")],
2343                Some(AutoindentMode::EachLine),
2344                cx,
2345            );
2346        }
2347
2348        if space_above && position.row > 0 && !self.is_line_blank(position.row - 1) {
2349            self.edit(
2350                [(position..position, "\n")],
2351                Some(AutoindentMode::EachLine),
2352                cx,
2353            );
2354            position.row += 1;
2355        }
2356
2357        if space_below
2358            && (position.row == self.max_point().row || !self.is_line_blank(position.row + 1))
2359        {
2360            self.edit(
2361                [(position..position, "\n")],
2362                Some(AutoindentMode::EachLine),
2363                cx,
2364            );
2365        }
2366
2367        self.end_transaction(cx);
2368
2369        position
2370    }
2371
2372    /// Applies the given remote operations to the buffer.
2373    pub fn apply_ops<I: IntoIterator<Item = Operation>>(&mut self, ops: I, cx: &mut Context<Self>) {
2374        self.pending_autoindent.take();
2375        let was_dirty = self.is_dirty();
2376        let old_version = self.version.clone();
2377        let mut deferred_ops = Vec::new();
2378        let buffer_ops = ops
2379            .into_iter()
2380            .filter_map(|op| match op {
2381                Operation::Buffer(op) => Some(op),
2382                _ => {
2383                    if self.can_apply_op(&op) {
2384                        self.apply_op(op, cx);
2385                    } else {
2386                        deferred_ops.push(op);
2387                    }
2388                    None
2389                }
2390            })
2391            .collect::<Vec<_>>();
2392        for operation in buffer_ops.iter() {
2393            self.send_operation(Operation::Buffer(operation.clone()), false, cx);
2394        }
2395        self.text.apply_ops(buffer_ops);
2396        self.deferred_ops.insert(deferred_ops);
2397        self.flush_deferred_ops(cx);
2398        self.did_edit(&old_version, was_dirty, cx);
2399        // Notify independently of whether the buffer was edited as the operations could include a
2400        // selection update.
2401        cx.notify();
2402    }
2403
2404    fn flush_deferred_ops(&mut self, cx: &mut Context<Self>) {
2405        let mut deferred_ops = Vec::new();
2406        for op in self.deferred_ops.drain().iter().cloned() {
2407            if self.can_apply_op(&op) {
2408                self.apply_op(op, cx);
2409            } else {
2410                deferred_ops.push(op);
2411            }
2412        }
2413        self.deferred_ops.insert(deferred_ops);
2414    }
2415
2416    pub fn has_deferred_ops(&self) -> bool {
2417        !self.deferred_ops.is_empty() || self.text.has_deferred_ops()
2418    }
2419
2420    fn can_apply_op(&self, operation: &Operation) -> bool {
2421        match operation {
2422            Operation::Buffer(_) => {
2423                unreachable!("buffer operations should never be applied at this layer")
2424            }
2425            Operation::UpdateDiagnostics {
2426                diagnostics: diagnostic_set,
2427                ..
2428            } => diagnostic_set.iter().all(|diagnostic| {
2429                self.text.can_resolve(&diagnostic.range.start)
2430                    && self.text.can_resolve(&diagnostic.range.end)
2431            }),
2432            Operation::UpdateSelections { selections, .. } => selections
2433                .iter()
2434                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
2435            Operation::UpdateCompletionTriggers { .. } => true,
2436        }
2437    }
2438
2439    fn apply_op(&mut self, operation: Operation, cx: &mut Context<Self>) {
2440        match operation {
2441            Operation::Buffer(_) => {
2442                unreachable!("buffer operations should never be applied at this layer")
2443            }
2444            Operation::UpdateDiagnostics {
2445                server_id,
2446                diagnostics: diagnostic_set,
2447                lamport_timestamp,
2448            } => {
2449                let snapshot = self.snapshot();
2450                self.apply_diagnostic_update(
2451                    server_id,
2452                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
2453                    lamport_timestamp,
2454                    cx,
2455                );
2456            }
2457            Operation::UpdateSelections {
2458                selections,
2459                lamport_timestamp,
2460                line_mode,
2461                cursor_shape,
2462            } => {
2463                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
2464                    if set.lamport_timestamp > lamport_timestamp {
2465                        return;
2466                    }
2467                }
2468
2469                self.remote_selections.insert(
2470                    lamport_timestamp.replica_id,
2471                    SelectionSet {
2472                        selections,
2473                        lamport_timestamp,
2474                        line_mode,
2475                        cursor_shape,
2476                    },
2477                );
2478                self.text.lamport_clock.observe(lamport_timestamp);
2479                self.non_text_state_update_count += 1;
2480            }
2481            Operation::UpdateCompletionTriggers {
2482                triggers,
2483                lamport_timestamp,
2484                server_id,
2485            } => {
2486                if triggers.is_empty() {
2487                    self.completion_triggers_per_language_server
2488                        .remove(&server_id);
2489                    self.completion_triggers = self
2490                        .completion_triggers_per_language_server
2491                        .values()
2492                        .flat_map(|triggers| triggers.into_iter().cloned())
2493                        .collect();
2494                } else {
2495                    self.completion_triggers_per_language_server
2496                        .insert(server_id, triggers.iter().cloned().collect());
2497                    self.completion_triggers.extend(triggers);
2498                }
2499                self.text.lamport_clock.observe(lamport_timestamp);
2500            }
2501        }
2502    }
2503
2504    fn apply_diagnostic_update(
2505        &mut self,
2506        server_id: LanguageServerId,
2507        diagnostics: DiagnosticSet,
2508        lamport_timestamp: clock::Lamport,
2509        cx: &mut Context<Self>,
2510    ) {
2511        if lamport_timestamp > self.diagnostics_timestamp {
2512            let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
2513            if diagnostics.is_empty() {
2514                if let Ok(ix) = ix {
2515                    self.diagnostics.remove(ix);
2516                }
2517            } else {
2518                match ix {
2519                    Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
2520                    Ok(ix) => self.diagnostics[ix].1 = diagnostics,
2521                };
2522            }
2523            self.diagnostics_timestamp = lamport_timestamp;
2524            self.non_text_state_update_count += 1;
2525            self.text.lamport_clock.observe(lamport_timestamp);
2526            cx.notify();
2527            cx.emit(BufferEvent::DiagnosticsUpdated);
2528        }
2529    }
2530
2531    fn send_operation(&mut self, operation: Operation, is_local: bool, cx: &mut Context<Self>) {
2532        self.was_changed();
2533        cx.emit(BufferEvent::Operation {
2534            operation,
2535            is_local,
2536        });
2537    }
2538
2539    /// Removes the selections for a given peer.
2540    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut Context<Self>) {
2541        self.remote_selections.remove(&replica_id);
2542        cx.notify();
2543    }
2544
2545    /// Undoes the most recent transaction.
2546    pub fn undo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2547        let was_dirty = self.is_dirty();
2548        let old_version = self.version.clone();
2549
2550        if let Some((transaction_id, operation)) = self.text.undo() {
2551            self.send_operation(Operation::Buffer(operation), true, cx);
2552            self.did_edit(&old_version, was_dirty, cx);
2553            Some(transaction_id)
2554        } else {
2555            None
2556        }
2557    }
2558
2559    /// Manually undoes a specific transaction in the buffer's undo history.
2560    pub fn undo_transaction(
2561        &mut self,
2562        transaction_id: TransactionId,
2563        cx: &mut Context<Self>,
2564    ) -> bool {
2565        let was_dirty = self.is_dirty();
2566        let old_version = self.version.clone();
2567        if let Some(operation) = self.text.undo_transaction(transaction_id) {
2568            self.send_operation(Operation::Buffer(operation), true, cx);
2569            self.did_edit(&old_version, was_dirty, cx);
2570            true
2571        } else {
2572            false
2573        }
2574    }
2575
2576    /// Manually undoes all changes after a given transaction in the buffer's undo history.
2577    pub fn undo_to_transaction(
2578        &mut self,
2579        transaction_id: TransactionId,
2580        cx: &mut Context<Self>,
2581    ) -> bool {
2582        let was_dirty = self.is_dirty();
2583        let old_version = self.version.clone();
2584
2585        let operations = self.text.undo_to_transaction(transaction_id);
2586        let undone = !operations.is_empty();
2587        for operation in operations {
2588            self.send_operation(Operation::Buffer(operation), true, cx);
2589        }
2590        if undone {
2591            self.did_edit(&old_version, was_dirty, cx)
2592        }
2593        undone
2594    }
2595
2596    pub fn undo_operations(&mut self, counts: HashMap<Lamport, u32>, cx: &mut Context<Buffer>) {
2597        let was_dirty = self.is_dirty();
2598        let operation = self.text.undo_operations(counts);
2599        let old_version = self.version.clone();
2600        self.send_operation(Operation::Buffer(operation), true, cx);
2601        self.did_edit(&old_version, was_dirty, cx);
2602    }
2603
2604    /// Manually redoes a specific transaction in the buffer's redo history.
2605    pub fn redo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2606        let was_dirty = self.is_dirty();
2607        let old_version = self.version.clone();
2608
2609        if let Some((transaction_id, operation)) = self.text.redo() {
2610            self.send_operation(Operation::Buffer(operation), true, cx);
2611            self.did_edit(&old_version, was_dirty, cx);
2612            Some(transaction_id)
2613        } else {
2614            None
2615        }
2616    }
2617
2618    /// Manually undoes all changes until a given transaction in the buffer's redo history.
2619    pub fn redo_to_transaction(
2620        &mut self,
2621        transaction_id: TransactionId,
2622        cx: &mut Context<Self>,
2623    ) -> bool {
2624        let was_dirty = self.is_dirty();
2625        let old_version = self.version.clone();
2626
2627        let operations = self.text.redo_to_transaction(transaction_id);
2628        let redone = !operations.is_empty();
2629        for operation in operations {
2630            self.send_operation(Operation::Buffer(operation), true, cx);
2631        }
2632        if redone {
2633            self.did_edit(&old_version, was_dirty, cx)
2634        }
2635        redone
2636    }
2637
2638    /// Override current completion triggers with the user-provided completion triggers.
2639    pub fn set_completion_triggers(
2640        &mut self,
2641        server_id: LanguageServerId,
2642        triggers: BTreeSet<String>,
2643        cx: &mut Context<Self>,
2644    ) {
2645        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2646        if triggers.is_empty() {
2647            self.completion_triggers_per_language_server
2648                .remove(&server_id);
2649            self.completion_triggers = self
2650                .completion_triggers_per_language_server
2651                .values()
2652                .flat_map(|triggers| triggers.into_iter().cloned())
2653                .collect();
2654        } else {
2655            self.completion_triggers_per_language_server
2656                .insert(server_id, triggers.clone());
2657            self.completion_triggers.extend(triggers.iter().cloned());
2658        }
2659        self.send_operation(
2660            Operation::UpdateCompletionTriggers {
2661                triggers: triggers.iter().cloned().collect(),
2662                lamport_timestamp: self.completion_triggers_timestamp,
2663                server_id,
2664            },
2665            true,
2666            cx,
2667        );
2668        cx.notify();
2669    }
2670
2671    /// Returns a list of strings which trigger a completion menu for this language.
2672    /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2673    pub fn completion_triggers(&self) -> &BTreeSet<String> {
2674        &self.completion_triggers
2675    }
2676
2677    /// Call this directly after performing edits to prevent the preview tab
2678    /// from being dismissed by those edits. It causes `should_dismiss_preview`
2679    /// to return false until there are additional edits.
2680    pub fn refresh_preview(&mut self) {
2681        self.preview_version = self.version.clone();
2682    }
2683
2684    /// Whether we should preserve the preview status of a tab containing this buffer.
2685    pub fn preserve_preview(&self) -> bool {
2686        !self.has_edits_since(&self.preview_version)
2687    }
2688}
2689
2690#[doc(hidden)]
2691#[cfg(any(test, feature = "test-support"))]
2692impl Buffer {
2693    pub fn edit_via_marked_text(
2694        &mut self,
2695        marked_string: &str,
2696        autoindent_mode: Option<AutoindentMode>,
2697        cx: &mut Context<Self>,
2698    ) {
2699        let edits = self.edits_for_marked_text(marked_string);
2700        self.edit(edits, autoindent_mode, cx);
2701    }
2702
2703    pub fn set_group_interval(&mut self, group_interval: Duration) {
2704        self.text.set_group_interval(group_interval);
2705    }
2706
2707    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize, cx: &mut Context<Self>)
2708    where
2709        T: rand::Rng,
2710    {
2711        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2712        let mut last_end = None;
2713        for _ in 0..old_range_count {
2714            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2715                break;
2716            }
2717
2718            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2719            let mut range = self.random_byte_range(new_start, rng);
2720            if rng.gen_bool(0.2) {
2721                mem::swap(&mut range.start, &mut range.end);
2722            }
2723            last_end = Some(range.end);
2724
2725            let new_text_len = rng.gen_range(0..10);
2726            let mut new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2727            new_text = new_text.to_uppercase();
2728
2729            edits.push((range, new_text));
2730        }
2731        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2732        self.edit(edits, None, cx);
2733    }
2734
2735    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut Context<Self>) {
2736        let was_dirty = self.is_dirty();
2737        let old_version = self.version.clone();
2738
2739        let ops = self.text.randomly_undo_redo(rng);
2740        if !ops.is_empty() {
2741            for op in ops {
2742                self.send_operation(Operation::Buffer(op), true, cx);
2743                self.did_edit(&old_version, was_dirty, cx);
2744            }
2745        }
2746    }
2747}
2748
2749impl EventEmitter<BufferEvent> for Buffer {}
2750
2751impl Deref for Buffer {
2752    type Target = TextBuffer;
2753
2754    fn deref(&self) -> &Self::Target {
2755        &self.text
2756    }
2757}
2758
2759impl BufferSnapshot {
2760    /// Returns [`IndentSize`] for a given line that respects user settings and
2761    /// language preferences.
2762    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2763        indent_size_for_line(self, row)
2764    }
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
3541        for (buffer_range, is_name) in buffer_ranges {
3542            let space_added = !text.is_empty() && buffer_range.start > last_buffer_range_end;
3543            if space_added {
3544                text.push(' ');
3545            }
3546            let before_append_len = text.len();
3547            let mut offset = buffer_range.start;
3548            chunks.seek(buffer_range.clone());
3549            for mut chunk in chunks.by_ref() {
3550                if chunk.text.len() > buffer_range.end - offset {
3551                    chunk.text = &chunk.text[0..(buffer_range.end - offset)];
3552                    offset = buffer_range.end;
3553                } else {
3554                    offset += chunk.text.len();
3555                }
3556                let style = chunk
3557                    .syntax_highlight_id
3558                    .zip(theme)
3559                    .and_then(|(highlight, theme)| highlight.style(theme));
3560                if let Some(style) = style {
3561                    let start = text.len();
3562                    let end = start + chunk.text.len();
3563                    highlight_ranges.push((start..end, style));
3564                }
3565                text.push_str(chunk.text);
3566                if offset >= buffer_range.end {
3567                    break;
3568                }
3569            }
3570            if is_name {
3571                let after_append_len = text.len();
3572                let start = if space_added && !name_ranges.is_empty() {
3573                    before_append_len - 1
3574                } else {
3575                    before_append_len
3576                };
3577                name_ranges.push(start..after_append_len);
3578            }
3579            last_buffer_range_end = buffer_range.end;
3580        }
3581
3582        Some(OutlineItem {
3583            depth: 0, // We'll calculate the depth later
3584            range: item_point_range,
3585            text,
3586            highlight_ranges,
3587            name_ranges,
3588            body_range: open_point.zip(close_point).map(|(start, end)| start..end),
3589            annotation_range: None,
3590        })
3591    }
3592
3593    pub fn function_body_fold_ranges<T: ToOffset>(
3594        &self,
3595        within: Range<T>,
3596    ) -> impl Iterator<Item = Range<usize>> + '_ {
3597        self.text_object_ranges(within, TreeSitterOptions::default())
3598            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
3599    }
3600
3601    /// For each grammar in the language, runs the provided
3602    /// [`tree_sitter::Query`] against the given range.
3603    pub fn matches(
3604        &self,
3605        range: Range<usize>,
3606        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
3607    ) -> SyntaxMapMatches {
3608        self.syntax.matches(range, self, query)
3609    }
3610
3611    pub fn all_bracket_ranges(
3612        &self,
3613        range: Range<usize>,
3614    ) -> impl Iterator<Item = BracketMatch> + '_ {
3615        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3616            grammar.brackets_config.as_ref().map(|c| &c.query)
3617        });
3618        let configs = matches
3619            .grammars()
3620            .iter()
3621            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
3622            .collect::<Vec<_>>();
3623
3624        iter::from_fn(move || {
3625            while let Some(mat) = matches.peek() {
3626                let mut open = None;
3627                let mut close = None;
3628                let config = &configs[mat.grammar_index];
3629                let pattern = &config.patterns[mat.pattern_index];
3630                for capture in mat.captures {
3631                    if capture.index == config.open_capture_ix {
3632                        open = Some(capture.node.byte_range());
3633                    } else if capture.index == config.close_capture_ix {
3634                        close = Some(capture.node.byte_range());
3635                    }
3636                }
3637
3638                matches.advance();
3639
3640                let Some((open_range, close_range)) = open.zip(close) else {
3641                    continue;
3642                };
3643
3644                let bracket_range = open_range.start..=close_range.end;
3645                if !bracket_range.overlaps(&range) {
3646                    continue;
3647                }
3648
3649                return Some(BracketMatch {
3650                    open_range,
3651                    close_range,
3652                    newline_only: pattern.newline_only,
3653                });
3654            }
3655            None
3656        })
3657    }
3658
3659    /// Returns bracket range pairs overlapping or adjacent to `range`
3660    pub fn bracket_ranges<T: ToOffset>(
3661        &self,
3662        range: Range<T>,
3663    ) -> impl Iterator<Item = BracketMatch> + '_ {
3664        // Find bracket pairs that *inclusively* contain the given range.
3665        let range = range.start.to_offset(self).saturating_sub(1)
3666            ..self.len().min(range.end.to_offset(self) + 1);
3667        self.all_bracket_ranges(range)
3668            .filter(|pair| !pair.newline_only)
3669    }
3670
3671    pub fn text_object_ranges<T: ToOffset>(
3672        &self,
3673        range: Range<T>,
3674        options: TreeSitterOptions,
3675    ) -> impl Iterator<Item = (Range<usize>, TextObject)> + '_ {
3676        let range = range.start.to_offset(self).saturating_sub(1)
3677            ..self.len().min(range.end.to_offset(self) + 1);
3678
3679        let mut matches =
3680            self.syntax
3681                .matches_with_options(range.clone(), &self.text, options, |grammar| {
3682                    grammar.text_object_config.as_ref().map(|c| &c.query)
3683                });
3684
3685        let configs = matches
3686            .grammars()
3687            .iter()
3688            .map(|grammar| grammar.text_object_config.as_ref())
3689            .collect::<Vec<_>>();
3690
3691        let mut captures = Vec::<(Range<usize>, TextObject)>::new();
3692
3693        iter::from_fn(move || loop {
3694            while let Some(capture) = captures.pop() {
3695                if capture.0.overlaps(&range) {
3696                    return Some(capture);
3697                }
3698            }
3699
3700            let mat = matches.peek()?;
3701
3702            let Some(config) = configs[mat.grammar_index].as_ref() else {
3703                matches.advance();
3704                continue;
3705            };
3706
3707            for capture in mat.captures {
3708                let Some(ix) = config
3709                    .text_objects_by_capture_ix
3710                    .binary_search_by_key(&capture.index, |e| e.0)
3711                    .ok()
3712                else {
3713                    continue;
3714                };
3715                let text_object = config.text_objects_by_capture_ix[ix].1;
3716                let byte_range = capture.node.byte_range();
3717
3718                let mut found = false;
3719                for (range, existing) in captures.iter_mut() {
3720                    if existing == &text_object {
3721                        range.start = range.start.min(byte_range.start);
3722                        range.end = range.end.max(byte_range.end);
3723                        found = true;
3724                        break;
3725                    }
3726                }
3727
3728                if !found {
3729                    captures.push((byte_range, text_object));
3730                }
3731            }
3732
3733            matches.advance();
3734        })
3735    }
3736
3737    /// Returns enclosing bracket ranges containing the given range
3738    pub fn enclosing_bracket_ranges<T: ToOffset>(
3739        &self,
3740        range: Range<T>,
3741    ) -> impl Iterator<Item = BracketMatch> + '_ {
3742        let range = range.start.to_offset(self)..range.end.to_offset(self);
3743
3744        self.bracket_ranges(range.clone()).filter(move |pair| {
3745            pair.open_range.start <= range.start && pair.close_range.end >= range.end
3746        })
3747    }
3748
3749    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3750    ///
3751    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3752    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3753        &self,
3754        range: Range<T>,
3755        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3756    ) -> Option<(Range<usize>, Range<usize>)> {
3757        let range = range.start.to_offset(self)..range.end.to_offset(self);
3758
3759        // Get the ranges of the innermost pair of brackets.
3760        let mut result: Option<(Range<usize>, Range<usize>)> = None;
3761
3762        for pair in self.enclosing_bracket_ranges(range.clone()) {
3763            if let Some(range_filter) = range_filter {
3764                if !range_filter(pair.open_range.clone(), pair.close_range.clone()) {
3765                    continue;
3766                }
3767            }
3768
3769            let len = pair.close_range.end - pair.open_range.start;
3770
3771            if let Some((existing_open, existing_close)) = &result {
3772                let existing_len = existing_close.end - existing_open.start;
3773                if len > existing_len {
3774                    continue;
3775                }
3776            }
3777
3778            result = Some((pair.open_range, pair.close_range));
3779        }
3780
3781        result
3782    }
3783
3784    /// Returns anchor ranges for any matches of the redaction query.
3785    /// The buffer can be associated with multiple languages, and the redaction query associated with each
3786    /// will be run on the relevant section of the buffer.
3787    pub fn redacted_ranges<T: ToOffset>(
3788        &self,
3789        range: Range<T>,
3790    ) -> impl Iterator<Item = Range<usize>> + '_ {
3791        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3792        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3793            grammar
3794                .redactions_config
3795                .as_ref()
3796                .map(|config| &config.query)
3797        });
3798
3799        let configs = syntax_matches
3800            .grammars()
3801            .iter()
3802            .map(|grammar| grammar.redactions_config.as_ref())
3803            .collect::<Vec<_>>();
3804
3805        iter::from_fn(move || {
3806            let redacted_range = syntax_matches
3807                .peek()
3808                .and_then(|mat| {
3809                    configs[mat.grammar_index].and_then(|config| {
3810                        mat.captures
3811                            .iter()
3812                            .find(|capture| capture.index == config.redaction_capture_ix)
3813                    })
3814                })
3815                .map(|mat| mat.node.byte_range());
3816            syntax_matches.advance();
3817            redacted_range
3818        })
3819    }
3820
3821    pub fn injections_intersecting_range<T: ToOffset>(
3822        &self,
3823        range: Range<T>,
3824    ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3825        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3826
3827        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3828            grammar
3829                .injection_config
3830                .as_ref()
3831                .map(|config| &config.query)
3832        });
3833
3834        let configs = syntax_matches
3835            .grammars()
3836            .iter()
3837            .map(|grammar| grammar.injection_config.as_ref())
3838            .collect::<Vec<_>>();
3839
3840        iter::from_fn(move || {
3841            let ranges = syntax_matches.peek().and_then(|mat| {
3842                let config = &configs[mat.grammar_index]?;
3843                let content_capture_range = mat.captures.iter().find_map(|capture| {
3844                    if capture.index == config.content_capture_ix {
3845                        Some(capture.node.byte_range())
3846                    } else {
3847                        None
3848                    }
3849                })?;
3850                let language = self.language_at(content_capture_range.start)?;
3851                Some((content_capture_range, language))
3852            });
3853            syntax_matches.advance();
3854            ranges
3855        })
3856    }
3857
3858    pub fn runnable_ranges(
3859        &self,
3860        offset_range: Range<usize>,
3861    ) -> impl Iterator<Item = RunnableRange> + '_ {
3862        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3863            grammar.runnable_config.as_ref().map(|config| &config.query)
3864        });
3865
3866        let test_configs = syntax_matches
3867            .grammars()
3868            .iter()
3869            .map(|grammar| grammar.runnable_config.as_ref())
3870            .collect::<Vec<_>>();
3871
3872        iter::from_fn(move || loop {
3873            let mat = syntax_matches.peek()?;
3874
3875            let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3876                let mut run_range = None;
3877                let full_range = mat.captures.iter().fold(
3878                    Range {
3879                        start: usize::MAX,
3880                        end: 0,
3881                    },
3882                    |mut acc, next| {
3883                        let byte_range = next.node.byte_range();
3884                        if acc.start > byte_range.start {
3885                            acc.start = byte_range.start;
3886                        }
3887                        if acc.end < byte_range.end {
3888                            acc.end = byte_range.end;
3889                        }
3890                        acc
3891                    },
3892                );
3893                if full_range.start > full_range.end {
3894                    // We did not find a full spanning range of this match.
3895                    return None;
3896                }
3897                let extra_captures: SmallVec<[_; 1]> =
3898                    SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3899                        test_configs
3900                            .extra_captures
3901                            .get(capture.index as usize)
3902                            .cloned()
3903                            .and_then(|tag_name| match tag_name {
3904                                RunnableCapture::Named(name) => {
3905                                    Some((capture.node.byte_range(), name))
3906                                }
3907                                RunnableCapture::Run => {
3908                                    let _ = run_range.insert(capture.node.byte_range());
3909                                    None
3910                                }
3911                            })
3912                    }));
3913                let run_range = run_range?;
3914                let tags = test_configs
3915                    .query
3916                    .property_settings(mat.pattern_index)
3917                    .iter()
3918                    .filter_map(|property| {
3919                        if *property.key == *"tag" {
3920                            property
3921                                .value
3922                                .as_ref()
3923                                .map(|value| RunnableTag(value.to_string().into()))
3924                        } else {
3925                            None
3926                        }
3927                    })
3928                    .collect();
3929                let extra_captures = extra_captures
3930                    .into_iter()
3931                    .map(|(range, name)| {
3932                        (
3933                            name.to_string(),
3934                            self.text_for_range(range.clone()).collect::<String>(),
3935                        )
3936                    })
3937                    .collect();
3938                // All tags should have the same range.
3939                Some(RunnableRange {
3940                    run_range,
3941                    full_range,
3942                    runnable: Runnable {
3943                        tags,
3944                        language: mat.language,
3945                        buffer: self.remote_id(),
3946                    },
3947                    extra_captures,
3948                    buffer_id: self.remote_id(),
3949                })
3950            });
3951
3952            syntax_matches.advance();
3953            if test_range.is_some() {
3954                // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
3955                // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
3956                return test_range;
3957            }
3958        })
3959    }
3960
3961    /// Returns selections for remote peers intersecting the given range.
3962    #[allow(clippy::type_complexity)]
3963    pub fn selections_in_range(
3964        &self,
3965        range: Range<Anchor>,
3966        include_local: bool,
3967    ) -> impl Iterator<
3968        Item = (
3969            ReplicaId,
3970            bool,
3971            CursorShape,
3972            impl Iterator<Item = &Selection<Anchor>> + '_,
3973        ),
3974    > + '_ {
3975        self.remote_selections
3976            .iter()
3977            .filter(move |(replica_id, set)| {
3978                (include_local || **replica_id != self.text.replica_id())
3979                    && !set.selections.is_empty()
3980            })
3981            .map(move |(replica_id, set)| {
3982                let start_ix = match set.selections.binary_search_by(|probe| {
3983                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
3984                }) {
3985                    Ok(ix) | Err(ix) => ix,
3986                };
3987                let end_ix = match set.selections.binary_search_by(|probe| {
3988                    probe.start.cmp(&range.end, self).then(Ordering::Less)
3989                }) {
3990                    Ok(ix) | Err(ix) => ix,
3991                };
3992
3993                (
3994                    *replica_id,
3995                    set.line_mode,
3996                    set.cursor_shape,
3997                    set.selections[start_ix..end_ix].iter(),
3998                )
3999            })
4000    }
4001
4002    /// Returns if the buffer contains any diagnostics.
4003    pub fn has_diagnostics(&self) -> bool {
4004        !self.diagnostics.is_empty()
4005    }
4006
4007    /// Returns all the diagnostics intersecting the given range.
4008    pub fn diagnostics_in_range<'a, T, O>(
4009        &'a self,
4010        search_range: Range<T>,
4011        reversed: bool,
4012    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
4013    where
4014        T: 'a + Clone + ToOffset,
4015        O: 'a + FromAnchor,
4016    {
4017        let mut iterators: Vec<_> = self
4018            .diagnostics
4019            .iter()
4020            .map(|(_, collection)| {
4021                collection
4022                    .range::<T, text::Anchor>(search_range.clone(), self, true, reversed)
4023                    .peekable()
4024            })
4025            .collect();
4026
4027        std::iter::from_fn(move || {
4028            let (next_ix, _) = iterators
4029                .iter_mut()
4030                .enumerate()
4031                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
4032                .min_by(|(_, a), (_, b)| {
4033                    let cmp = a
4034                        .range
4035                        .start
4036                        .cmp(&b.range.start, self)
4037                        // when range is equal, sort by diagnostic severity
4038                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
4039                        // and stabilize order with group_id
4040                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
4041                    if reversed {
4042                        cmp.reverse()
4043                    } else {
4044                        cmp
4045                    }
4046                })?;
4047            iterators[next_ix]
4048                .next()
4049                .map(|DiagnosticEntry { range, diagnostic }| DiagnosticEntry {
4050                    diagnostic,
4051                    range: FromAnchor::from_anchor(&range.start, self)
4052                        ..FromAnchor::from_anchor(&range.end, self),
4053                })
4054        })
4055    }
4056
4057    /// Returns all the diagnostic groups associated with the given
4058    /// language server ID. If no language server ID is provided,
4059    /// all diagnostics groups are returned.
4060    pub fn diagnostic_groups(
4061        &self,
4062        language_server_id: Option<LanguageServerId>,
4063    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
4064        let mut groups = Vec::new();
4065
4066        if let Some(language_server_id) = language_server_id {
4067            if let Ok(ix) = self
4068                .diagnostics
4069                .binary_search_by_key(&language_server_id, |e| e.0)
4070            {
4071                self.diagnostics[ix]
4072                    .1
4073                    .groups(language_server_id, &mut groups, self);
4074            }
4075        } else {
4076            for (language_server_id, diagnostics) in self.diagnostics.iter() {
4077                diagnostics.groups(*language_server_id, &mut groups, self);
4078            }
4079        }
4080
4081        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
4082            let a_start = &group_a.entries[group_a.primary_ix].range.start;
4083            let b_start = &group_b.entries[group_b.primary_ix].range.start;
4084            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
4085        });
4086
4087        groups
4088    }
4089
4090    /// Returns an iterator over the diagnostics for the given group.
4091    pub fn diagnostic_group<O>(
4092        &self,
4093        group_id: usize,
4094    ) -> impl Iterator<Item = DiagnosticEntry<O>> + '_
4095    where
4096        O: FromAnchor + 'static,
4097    {
4098        self.diagnostics
4099            .iter()
4100            .flat_map(move |(_, set)| set.group(group_id, self))
4101    }
4102
4103    /// An integer version number that accounts for all updates besides
4104    /// the buffer's text itself (which is versioned via a version vector).
4105    pub fn non_text_state_update_count(&self) -> usize {
4106        self.non_text_state_update_count
4107    }
4108
4109    /// Returns a snapshot of underlying file.
4110    pub fn file(&self) -> Option<&Arc<dyn File>> {
4111        self.file.as_ref()
4112    }
4113
4114    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
4115    pub fn resolve_file_path(&self, cx: &App, include_root: bool) -> Option<PathBuf> {
4116        if let Some(file) = self.file() {
4117            if file.path().file_name().is_none() || include_root {
4118                Some(file.full_path(cx))
4119            } else {
4120                Some(file.path().to_path_buf())
4121            }
4122        } else {
4123            None
4124        }
4125    }
4126}
4127
4128fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
4129    indent_size_for_text(text.chars_at(Point::new(row, 0)))
4130}
4131
4132fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
4133    let mut result = IndentSize::spaces(0);
4134    for c in text {
4135        let kind = match c {
4136            ' ' => IndentKind::Space,
4137            '\t' => IndentKind::Tab,
4138            _ => break,
4139        };
4140        if result.len == 0 {
4141            result.kind = kind;
4142        }
4143        result.len += 1;
4144    }
4145    result
4146}
4147
4148impl Clone for BufferSnapshot {
4149    fn clone(&self) -> Self {
4150        Self {
4151            text: self.text.clone(),
4152            syntax: self.syntax.clone(),
4153            file: self.file.clone(),
4154            remote_selections: self.remote_selections.clone(),
4155            diagnostics: self.diagnostics.clone(),
4156            language: self.language.clone(),
4157            non_text_state_update_count: self.non_text_state_update_count,
4158        }
4159    }
4160}
4161
4162impl Deref for BufferSnapshot {
4163    type Target = text::BufferSnapshot;
4164
4165    fn deref(&self) -> &Self::Target {
4166        &self.text
4167    }
4168}
4169
4170unsafe impl Send for BufferChunks<'_> {}
4171
4172impl<'a> BufferChunks<'a> {
4173    pub(crate) fn new(
4174        text: &'a Rope,
4175        range: Range<usize>,
4176        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
4177        diagnostics: bool,
4178        buffer_snapshot: Option<&'a BufferSnapshot>,
4179    ) -> Self {
4180        let mut highlights = None;
4181        if let Some((captures, highlight_maps)) = syntax {
4182            highlights = Some(BufferChunkHighlights {
4183                captures,
4184                next_capture: None,
4185                stack: Default::default(),
4186                highlight_maps,
4187            })
4188        }
4189
4190        let diagnostic_endpoints = diagnostics.then(|| Vec::new().into_iter().peekable());
4191        let chunks = text.chunks_in_range(range.clone());
4192
4193        let mut this = BufferChunks {
4194            range,
4195            buffer_snapshot,
4196            chunks,
4197            diagnostic_endpoints,
4198            error_depth: 0,
4199            warning_depth: 0,
4200            information_depth: 0,
4201            hint_depth: 0,
4202            unnecessary_depth: 0,
4203            highlights,
4204        };
4205        this.initialize_diagnostic_endpoints();
4206        this
4207    }
4208
4209    /// Seeks to the given byte offset in the buffer.
4210    pub fn seek(&mut self, range: Range<usize>) {
4211        let old_range = std::mem::replace(&mut self.range, range.clone());
4212        self.chunks.set_range(self.range.clone());
4213        if let Some(highlights) = self.highlights.as_mut() {
4214            if old_range.start <= self.range.start && old_range.end >= self.range.end {
4215                // Reuse existing highlights stack, as the new range is a subrange of the old one.
4216                highlights
4217                    .stack
4218                    .retain(|(end_offset, _)| *end_offset > range.start);
4219                if let Some(capture) = &highlights.next_capture {
4220                    if range.start >= capture.node.start_byte() {
4221                        let next_capture_end = capture.node.end_byte();
4222                        if range.start < next_capture_end {
4223                            highlights.stack.push((
4224                                next_capture_end,
4225                                highlights.highlight_maps[capture.grammar_index].get(capture.index),
4226                            ));
4227                        }
4228                        highlights.next_capture.take();
4229                    }
4230                }
4231            } else if let Some(snapshot) = self.buffer_snapshot {
4232                let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
4233                *highlights = BufferChunkHighlights {
4234                    captures,
4235                    next_capture: None,
4236                    stack: Default::default(),
4237                    highlight_maps,
4238                };
4239            } else {
4240                // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
4241                // Seeking such BufferChunks is not supported.
4242                debug_assert!(false, "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot");
4243            }
4244
4245            highlights.captures.set_byte_range(self.range.clone());
4246            self.initialize_diagnostic_endpoints();
4247        }
4248    }
4249
4250    fn initialize_diagnostic_endpoints(&mut self) {
4251        if let Some(diagnostics) = self.diagnostic_endpoints.as_mut() {
4252            if let Some(buffer) = self.buffer_snapshot {
4253                let mut diagnostic_endpoints = Vec::new();
4254                for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
4255                    diagnostic_endpoints.push(DiagnosticEndpoint {
4256                        offset: entry.range.start,
4257                        is_start: true,
4258                        severity: entry.diagnostic.severity,
4259                        is_unnecessary: entry.diagnostic.is_unnecessary,
4260                    });
4261                    diagnostic_endpoints.push(DiagnosticEndpoint {
4262                        offset: entry.range.end,
4263                        is_start: false,
4264                        severity: entry.diagnostic.severity,
4265                        is_unnecessary: entry.diagnostic.is_unnecessary,
4266                    });
4267                }
4268                diagnostic_endpoints
4269                    .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
4270                *diagnostics = diagnostic_endpoints.into_iter().peekable();
4271                self.hint_depth = 0;
4272                self.error_depth = 0;
4273                self.warning_depth = 0;
4274                self.information_depth = 0;
4275            }
4276        }
4277    }
4278
4279    /// The current byte offset in the buffer.
4280    pub fn offset(&self) -> usize {
4281        self.range.start
4282    }
4283
4284    pub fn range(&self) -> Range<usize> {
4285        self.range.clone()
4286    }
4287
4288    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
4289        let depth = match endpoint.severity {
4290            DiagnosticSeverity::ERROR => &mut self.error_depth,
4291            DiagnosticSeverity::WARNING => &mut self.warning_depth,
4292            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
4293            DiagnosticSeverity::HINT => &mut self.hint_depth,
4294            _ => return,
4295        };
4296        if endpoint.is_start {
4297            *depth += 1;
4298        } else {
4299            *depth -= 1;
4300        }
4301
4302        if endpoint.is_unnecessary {
4303            if endpoint.is_start {
4304                self.unnecessary_depth += 1;
4305            } else {
4306                self.unnecessary_depth -= 1;
4307            }
4308        }
4309    }
4310
4311    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
4312        if self.error_depth > 0 {
4313            Some(DiagnosticSeverity::ERROR)
4314        } else if self.warning_depth > 0 {
4315            Some(DiagnosticSeverity::WARNING)
4316        } else if self.information_depth > 0 {
4317            Some(DiagnosticSeverity::INFORMATION)
4318        } else if self.hint_depth > 0 {
4319            Some(DiagnosticSeverity::HINT)
4320        } else {
4321            None
4322        }
4323    }
4324
4325    fn current_code_is_unnecessary(&self) -> bool {
4326        self.unnecessary_depth > 0
4327    }
4328}
4329
4330impl<'a> Iterator for BufferChunks<'a> {
4331    type Item = Chunk<'a>;
4332
4333    fn next(&mut self) -> Option<Self::Item> {
4334        let mut next_capture_start = usize::MAX;
4335        let mut next_diagnostic_endpoint = usize::MAX;
4336
4337        if let Some(highlights) = self.highlights.as_mut() {
4338            while let Some((parent_capture_end, _)) = highlights.stack.last() {
4339                if *parent_capture_end <= self.range.start {
4340                    highlights.stack.pop();
4341                } else {
4342                    break;
4343                }
4344            }
4345
4346            if highlights.next_capture.is_none() {
4347                highlights.next_capture = highlights.captures.next();
4348            }
4349
4350            while let Some(capture) = highlights.next_capture.as_ref() {
4351                if self.range.start < capture.node.start_byte() {
4352                    next_capture_start = capture.node.start_byte();
4353                    break;
4354                } else {
4355                    let highlight_id =
4356                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
4357                    highlights
4358                        .stack
4359                        .push((capture.node.end_byte(), highlight_id));
4360                    highlights.next_capture = highlights.captures.next();
4361                }
4362            }
4363        }
4364
4365        let mut diagnostic_endpoints = std::mem::take(&mut self.diagnostic_endpoints);
4366        if let Some(diagnostic_endpoints) = diagnostic_endpoints.as_mut() {
4367            while let Some(endpoint) = diagnostic_endpoints.peek().copied() {
4368                if endpoint.offset <= self.range.start {
4369                    self.update_diagnostic_depths(endpoint);
4370                    diagnostic_endpoints.next();
4371                } else {
4372                    next_diagnostic_endpoint = endpoint.offset;
4373                    break;
4374                }
4375            }
4376        }
4377        self.diagnostic_endpoints = diagnostic_endpoints;
4378
4379        if let Some(chunk) = self.chunks.peek() {
4380            let chunk_start = self.range.start;
4381            let mut chunk_end = (self.chunks.offset() + chunk.len())
4382                .min(next_capture_start)
4383                .min(next_diagnostic_endpoint);
4384            let mut highlight_id = None;
4385            if let Some(highlights) = self.highlights.as_ref() {
4386                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
4387                    chunk_end = chunk_end.min(*parent_capture_end);
4388                    highlight_id = Some(*parent_highlight_id);
4389                }
4390            }
4391
4392            let slice =
4393                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
4394            self.range.start = chunk_end;
4395            if self.range.start == self.chunks.offset() + chunk.len() {
4396                self.chunks.next().unwrap();
4397            }
4398
4399            Some(Chunk {
4400                text: slice,
4401                syntax_highlight_id: highlight_id,
4402                diagnostic_severity: self.current_diagnostic_severity(),
4403                is_unnecessary: self.current_code_is_unnecessary(),
4404                ..Default::default()
4405            })
4406        } else {
4407            None
4408        }
4409    }
4410}
4411
4412impl operation_queue::Operation for Operation {
4413    fn lamport_timestamp(&self) -> clock::Lamport {
4414        match self {
4415            Operation::Buffer(_) => {
4416                unreachable!("buffer operations should never be deferred at this layer")
4417            }
4418            Operation::UpdateDiagnostics {
4419                lamport_timestamp, ..
4420            }
4421            | Operation::UpdateSelections {
4422                lamport_timestamp, ..
4423            }
4424            | Operation::UpdateCompletionTriggers {
4425                lamport_timestamp, ..
4426            } => *lamport_timestamp,
4427        }
4428    }
4429}
4430
4431impl Default for Diagnostic {
4432    fn default() -> Self {
4433        Self {
4434            source: Default::default(),
4435            code: None,
4436            severity: DiagnosticSeverity::ERROR,
4437            message: Default::default(),
4438            group_id: 0,
4439            is_primary: false,
4440            is_disk_based: false,
4441            is_unnecessary: false,
4442            data: None,
4443        }
4444    }
4445}
4446
4447impl IndentSize {
4448    /// Returns an [`IndentSize`] representing the given spaces.
4449    pub fn spaces(len: u32) -> Self {
4450        Self {
4451            len,
4452            kind: IndentKind::Space,
4453        }
4454    }
4455
4456    /// Returns an [`IndentSize`] representing a tab.
4457    pub fn tab() -> Self {
4458        Self {
4459            len: 1,
4460            kind: IndentKind::Tab,
4461        }
4462    }
4463
4464    /// An iterator over the characters represented by this [`IndentSize`].
4465    pub fn chars(&self) -> impl Iterator<Item = char> {
4466        iter::repeat(self.char()).take(self.len as usize)
4467    }
4468
4469    /// The character representation of this [`IndentSize`].
4470    pub fn char(&self) -> char {
4471        match self.kind {
4472            IndentKind::Space => ' ',
4473            IndentKind::Tab => '\t',
4474        }
4475    }
4476
4477    /// Consumes the current [`IndentSize`] and returns a new one that has
4478    /// been shrunk or enlarged by the given size along the given direction.
4479    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4480        match direction {
4481            Ordering::Less => {
4482                if self.kind == size.kind && self.len >= size.len {
4483                    self.len -= size.len;
4484                }
4485            }
4486            Ordering::Equal => {}
4487            Ordering::Greater => {
4488                if self.len == 0 {
4489                    self = size;
4490                } else if self.kind == size.kind {
4491                    self.len += size.len;
4492                }
4493            }
4494        }
4495        self
4496    }
4497
4498    pub fn len_with_expanded_tabs(&self, tab_size: NonZeroU32) -> usize {
4499        match self.kind {
4500            IndentKind::Space => self.len as usize,
4501            IndentKind::Tab => self.len as usize * tab_size.get() as usize,
4502        }
4503    }
4504}
4505
4506#[cfg(any(test, feature = "test-support"))]
4507pub struct TestFile {
4508    pub path: Arc<Path>,
4509    pub root_name: String,
4510    pub local_root: Option<PathBuf>,
4511}
4512
4513#[cfg(any(test, feature = "test-support"))]
4514impl File for TestFile {
4515    fn path(&self) -> &Arc<Path> {
4516        &self.path
4517    }
4518
4519    fn full_path(&self, _: &gpui::App) -> PathBuf {
4520        PathBuf::from(&self.root_name).join(self.path.as_ref())
4521    }
4522
4523    fn as_local(&self) -> Option<&dyn LocalFile> {
4524        if self.local_root.is_some() {
4525            Some(self)
4526        } else {
4527            None
4528        }
4529    }
4530
4531    fn disk_state(&self) -> DiskState {
4532        unimplemented!()
4533    }
4534
4535    fn file_name<'a>(&'a self, _: &'a gpui::App) -> &'a std::ffi::OsStr {
4536        self.path().file_name().unwrap_or(self.root_name.as_ref())
4537    }
4538
4539    fn worktree_id(&self, _: &App) -> WorktreeId {
4540        WorktreeId::from_usize(0)
4541    }
4542
4543    fn as_any(&self) -> &dyn std::any::Any {
4544        unimplemented!()
4545    }
4546
4547    fn to_proto(&self, _: &App) -> rpc::proto::File {
4548        unimplemented!()
4549    }
4550
4551    fn is_private(&self) -> bool {
4552        false
4553    }
4554}
4555
4556#[cfg(any(test, feature = "test-support"))]
4557impl LocalFile for TestFile {
4558    fn abs_path(&self, _cx: &App) -> PathBuf {
4559        PathBuf::from(self.local_root.as_ref().unwrap())
4560            .join(&self.root_name)
4561            .join(self.path.as_ref())
4562    }
4563
4564    fn load(&self, _cx: &App) -> Task<Result<String>> {
4565        unimplemented!()
4566    }
4567
4568    fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
4569        unimplemented!()
4570    }
4571}
4572
4573pub(crate) fn contiguous_ranges(
4574    values: impl Iterator<Item = u32>,
4575    max_len: usize,
4576) -> impl Iterator<Item = Range<u32>> {
4577    let mut values = values;
4578    let mut current_range: Option<Range<u32>> = None;
4579    std::iter::from_fn(move || loop {
4580        if let Some(value) = values.next() {
4581            if let Some(range) = &mut current_range {
4582                if value == range.end && range.len() < max_len {
4583                    range.end += 1;
4584                    continue;
4585                }
4586            }
4587
4588            let prev_range = current_range.clone();
4589            current_range = Some(value..(value + 1));
4590            if prev_range.is_some() {
4591                return prev_range;
4592            }
4593        } else {
4594            return current_range.take();
4595        }
4596    })
4597}
4598
4599#[derive(Default, Debug)]
4600pub struct CharClassifier {
4601    scope: Option<LanguageScope>,
4602    for_completion: bool,
4603    ignore_punctuation: bool,
4604}
4605
4606impl CharClassifier {
4607    pub fn new(scope: Option<LanguageScope>) -> Self {
4608        Self {
4609            scope,
4610            for_completion: false,
4611            ignore_punctuation: false,
4612        }
4613    }
4614
4615    pub fn for_completion(self, for_completion: bool) -> Self {
4616        Self {
4617            for_completion,
4618            ..self
4619        }
4620    }
4621
4622    pub fn ignore_punctuation(self, ignore_punctuation: bool) -> Self {
4623        Self {
4624            ignore_punctuation,
4625            ..self
4626        }
4627    }
4628
4629    pub fn is_whitespace(&self, c: char) -> bool {
4630        self.kind(c) == CharKind::Whitespace
4631    }
4632
4633    pub fn is_word(&self, c: char) -> bool {
4634        self.kind(c) == CharKind::Word
4635    }
4636
4637    pub fn is_punctuation(&self, c: char) -> bool {
4638        self.kind(c) == CharKind::Punctuation
4639    }
4640
4641    pub fn kind_with(&self, c: char, ignore_punctuation: bool) -> CharKind {
4642        if c.is_whitespace() {
4643            return CharKind::Whitespace;
4644        } else if c.is_alphanumeric() || c == '_' {
4645            return CharKind::Word;
4646        }
4647
4648        if let Some(scope) = &self.scope {
4649            if let Some(characters) = scope.word_characters() {
4650                if characters.contains(&c) {
4651                    if c == '-' && !self.for_completion && !ignore_punctuation {
4652                        return CharKind::Punctuation;
4653                    }
4654                    return CharKind::Word;
4655                }
4656            }
4657        }
4658
4659        if ignore_punctuation {
4660            CharKind::Word
4661        } else {
4662            CharKind::Punctuation
4663        }
4664    }
4665
4666    pub fn kind(&self, c: char) -> CharKind {
4667        self.kind_with(c, self.ignore_punctuation)
4668    }
4669}
4670
4671/// Find all of the ranges of whitespace that occur at the ends of lines
4672/// in the given rope.
4673///
4674/// This could also be done with a regex search, but this implementation
4675/// avoids copying text.
4676pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4677    let mut ranges = Vec::new();
4678
4679    let mut offset = 0;
4680    let mut prev_chunk_trailing_whitespace_range = 0..0;
4681    for chunk in rope.chunks() {
4682        let mut prev_line_trailing_whitespace_range = 0..0;
4683        for (i, line) in chunk.split('\n').enumerate() {
4684            let line_end_offset = offset + line.len();
4685            let trimmed_line_len = line.trim_end_matches([' ', '\t']).len();
4686            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4687
4688            if i == 0 && trimmed_line_len == 0 {
4689                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4690            }
4691            if !prev_line_trailing_whitespace_range.is_empty() {
4692                ranges.push(prev_line_trailing_whitespace_range);
4693            }
4694
4695            offset = line_end_offset + 1;
4696            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4697        }
4698
4699        offset -= 1;
4700        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4701    }
4702
4703    if !prev_chunk_trailing_whitespace_range.is_empty() {
4704        ranges.push(prev_chunk_trailing_whitespace_range);
4705    }
4706
4707    ranges
4708}