buffer.rs

   1pub use crate::{
   2    Grammar, Language, LanguageRegistry,
   3    diagnostic_set::DiagnosticSet,
   4    highlight_map::{HighlightId, HighlightMap},
   5    proto,
   6};
   7use crate::{
   8    LanguageScope, Outline, OutlineConfig, RunnableCapture, RunnableTag, TextObject,
   9    TreeSitterOptions,
  10    diagnostic_set::{DiagnosticEntry, DiagnosticGroup},
  11    language_settings::{LanguageSettings, language_settings},
  12    outline::OutlineItem,
  13    syntax_map::{
  14        SyntaxLayer, SyntaxMap, SyntaxMapCapture, SyntaxMapCaptures, SyntaxMapMatch,
  15        SyntaxMapMatches, SyntaxSnapshot, ToTreeSitterPoint,
  16    },
  17    task_context::RunnableRange,
  18    text_diff::text_diff,
  19};
  20use anyhow::{Context as _, Result, anyhow};
  21use async_watch as watch;
  22use clock::Lamport;
  23pub use clock::ReplicaId;
  24use collections::HashMap;
  25use fs::MTime;
  26use futures::channel::oneshot;
  27use gpui::{
  28    AnyElement, App, AppContext as _, Context, Entity, EventEmitter, HighlightStyle, Pixels,
  29    SharedString, StyledText, Task, TaskLabel, TextStyle, Window,
  30};
  31use lsp::{LanguageServerId, NumberOrString};
  32use parking_lot::Mutex;
  33use schemars::JsonSchema;
  34use serde::{Deserialize, Serialize};
  35use serde_json::Value;
  36use settings::WorktreeId;
  37use smallvec::SmallVec;
  38use smol::future::yield_now;
  39use std::{
  40    any::Any,
  41    borrow::Cow,
  42    cell::Cell,
  43    cmp::{self, Ordering, Reverse},
  44    collections::{BTreeMap, BTreeSet},
  45    ffi::OsStr,
  46    fmt,
  47    future::Future,
  48    iter::{self, Iterator, Peekable},
  49    mem,
  50    num::NonZeroU32,
  51    ops::{Deref, DerefMut, Range},
  52    path::{Path, PathBuf},
  53    rc, str,
  54    sync::{Arc, LazyLock},
  55    time::{Duration, Instant},
  56    vec,
  57};
  58use sum_tree::TreeMap;
  59use text::operation_queue::OperationQueue;
  60use text::*;
  61pub use text::{
  62    Anchor, Bias, Buffer as TextBuffer, BufferId, BufferSnapshot as TextBufferSnapshot, Edit,
  63    OffsetRangeExt, OffsetUtf16, Patch, Point, PointUtf16, Rope, Selection, SelectionGoal,
  64    Subscription, TextDimension, TextSummary, ToOffset, ToOffsetUtf16, ToPoint, ToPointUtf16,
  65    Transaction, TransactionId, Unclipped,
  66};
  67use theme::{ActiveTheme as _, SyntaxTheme};
  68#[cfg(any(test, feature = "test-support"))]
  69use util::RandomCharIter;
  70use util::{RangeExt, debug_panic, maybe};
  71
  72#[cfg(any(test, feature = "test-support"))]
  73pub use {tree_sitter_rust, tree_sitter_typescript};
  74
  75pub use lsp::DiagnosticSeverity;
  76
  77/// A label for the background task spawned by the buffer to compute
  78/// a diff against the contents of its file.
  79pub static BUFFER_DIFF_TASK: LazyLock<TaskLabel> = LazyLock::new(TaskLabel::new);
  80
  81/// Indicate whether a [`Buffer`] has permissions to edit.
  82#[derive(PartialEq, Clone, Copy, Debug)]
  83pub enum Capability {
  84    /// The buffer is a mutable replica.
  85    ReadWrite,
  86    /// The buffer is a read-only replica.
  87    ReadOnly,
  88}
  89
  90pub type BufferRow = u32;
  91
  92/// An in-memory representation of a source code file, including its text,
  93/// syntax trees, git status, and diagnostics.
  94pub struct Buffer {
  95    text: TextBuffer,
  96    branch_state: Option<BufferBranchState>,
  97    /// Filesystem state, `None` when there is no path.
  98    file: Option<Arc<dyn File>>,
  99    /// The mtime of the file when this buffer was last loaded from
 100    /// or saved to disk.
 101    saved_mtime: Option<MTime>,
 102    /// The version vector when this buffer was last loaded from
 103    /// or saved to disk.
 104    saved_version: clock::Global,
 105    preview_version: clock::Global,
 106    transaction_depth: usize,
 107    was_dirty_before_starting_transaction: Option<bool>,
 108    reload_task: Option<Task<Result<()>>>,
 109    language: Option<Arc<Language>>,
 110    autoindent_requests: Vec<Arc<AutoindentRequest>>,
 111    pending_autoindent: Option<Task<()>>,
 112    sync_parse_timeout: Duration,
 113    syntax_map: Mutex<SyntaxMap>,
 114    reparse: Option<Task<()>>,
 115    parse_status: (watch::Sender<ParseStatus>, watch::Receiver<ParseStatus>),
 116    non_text_state_update_count: usize,
 117    diagnostics: SmallVec<[(LanguageServerId, DiagnosticSet); 2]>,
 118    remote_selections: TreeMap<ReplicaId, SelectionSet>,
 119    diagnostics_timestamp: clock::Lamport,
 120    completion_triggers: BTreeSet<String>,
 121    completion_triggers_per_language_server: HashMap<LanguageServerId, BTreeSet<String>>,
 122    completion_triggers_timestamp: clock::Lamport,
 123    deferred_ops: OperationQueue<Operation>,
 124    capability: Capability,
 125    has_conflict: bool,
 126    /// Memoize calls to has_changes_since(saved_version).
 127    /// The contents of a cell are (self.version, has_changes) at the time of a last call.
 128    has_unsaved_edits: Cell<(clock::Global, bool)>,
 129    change_bits: Vec<rc::Weak<Cell<bool>>>,
 130    _subscriptions: Vec<gpui::Subscription>,
 131}
 132
 133#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 134pub enum ParseStatus {
 135    Idle,
 136    Parsing,
 137}
 138
 139struct BufferBranchState {
 140    base_buffer: Entity<Buffer>,
 141    merged_operations: Vec<Lamport>,
 142}
 143
 144/// An immutable, cheaply cloneable representation of a fixed
 145/// state of a buffer.
 146pub struct BufferSnapshot {
 147    pub text: text::BufferSnapshot,
 148    pub(crate) syntax: SyntaxSnapshot,
 149    file: Option<Arc<dyn File>>,
 150    diagnostics: SmallVec<[(LanguageServerId, DiagnosticSet); 2]>,
 151    remote_selections: TreeMap<ReplicaId, SelectionSet>,
 152    language: Option<Arc<Language>>,
 153    non_text_state_update_count: usize,
 154}
 155
 156/// The kind and amount of indentation in a particular line. For now,
 157/// assumes that indentation is all the same character.
 158#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
 159pub struct IndentSize {
 160    /// The number of bytes that comprise the indentation.
 161    pub len: u32,
 162    /// The kind of whitespace used for indentation.
 163    pub kind: IndentKind,
 164}
 165
 166/// A whitespace character that's used for indentation.
 167#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
 168pub enum IndentKind {
 169    /// An ASCII space character.
 170    #[default]
 171    Space,
 172    /// An ASCII tab character.
 173    Tab,
 174}
 175
 176/// The shape of a selection cursor.
 177#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
 178#[serde(rename_all = "snake_case")]
 179pub enum CursorShape {
 180    /// A vertical bar
 181    #[default]
 182    Bar,
 183    /// A block that surrounds the following character
 184    Block,
 185    /// An underline that runs along the following character
 186    Underline,
 187    /// A box drawn around the following character
 188    Hollow,
 189}
 190
 191#[derive(Clone, Debug)]
 192struct SelectionSet {
 193    line_mode: bool,
 194    cursor_shape: CursorShape,
 195    selections: Arc<[Selection<Anchor>]>,
 196    lamport_timestamp: clock::Lamport,
 197}
 198
 199/// A diagnostic associated with a certain range of a buffer.
 200#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
 201pub struct Diagnostic {
 202    /// The name of the service that produced this diagnostic.
 203    pub source: Option<String>,
 204    /// A machine-readable code that identifies this diagnostic.
 205    pub code: Option<NumberOrString>,
 206    /// Whether this diagnostic is a hint, warning, or error.
 207    pub severity: DiagnosticSeverity,
 208    /// The human-readable message associated with this diagnostic.
 209    pub message: String,
 210    /// An id that identifies the group to which this diagnostic belongs.
 211    ///
 212    /// When a language server produces a diagnostic with
 213    /// one or more associated diagnostics, those diagnostics are all
 214    /// assigned a single group ID.
 215    pub group_id: usize,
 216    /// Whether this diagnostic is the primary diagnostic for its group.
 217    ///
 218    /// In a given group, the primary diagnostic is the top-level diagnostic
 219    /// returned by the language server. The non-primary diagnostics are the
 220    /// associated diagnostics.
 221    pub is_primary: bool,
 222    /// Whether this diagnostic is considered to originate from an analysis of
 223    /// files on disk, as opposed to any unsaved buffer contents. This is a
 224    /// property of a given diagnostic source, and is configured for a given
 225    /// language server via the [`LspAdapter::disk_based_diagnostic_sources`](crate::LspAdapter::disk_based_diagnostic_sources) method
 226    /// for the language server.
 227    pub is_disk_based: bool,
 228    /// Whether this diagnostic marks unnecessary code.
 229    pub is_unnecessary: bool,
 230    /// Data from language server that produced this diagnostic. Passed back to the LS when we request code actions for this diagnostic.
 231    pub data: Option<Value>,
 232}
 233
 234/// An operation used to synchronize this buffer with its other replicas.
 235#[derive(Clone, Debug, PartialEq)]
 236pub enum Operation {
 237    /// A text operation.
 238    Buffer(text::Operation),
 239
 240    /// An update to the buffer's diagnostics.
 241    UpdateDiagnostics {
 242        /// The id of the language server that produced the new diagnostics.
 243        server_id: LanguageServerId,
 244        /// The diagnostics.
 245        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
 246        /// The buffer's lamport timestamp.
 247        lamport_timestamp: clock::Lamport,
 248    },
 249
 250    /// An update to the most recent selections in this buffer.
 251    UpdateSelections {
 252        /// The selections.
 253        selections: Arc<[Selection<Anchor>]>,
 254        /// The buffer's lamport timestamp.
 255        lamport_timestamp: clock::Lamport,
 256        /// Whether the selections are in 'line mode'.
 257        line_mode: bool,
 258        /// The [`CursorShape`] associated with these selections.
 259        cursor_shape: CursorShape,
 260    },
 261
 262    /// An update to the characters that should trigger autocompletion
 263    /// for this buffer.
 264    UpdateCompletionTriggers {
 265        /// The characters that trigger autocompletion.
 266        triggers: Vec<String>,
 267        /// The buffer's lamport timestamp.
 268        lamport_timestamp: clock::Lamport,
 269        /// The language server ID.
 270        server_id: LanguageServerId,
 271    },
 272}
 273
 274/// An event that occurs in a buffer.
 275#[derive(Clone, Debug, PartialEq)]
 276pub enum BufferEvent {
 277    /// The buffer was changed in a way that must be
 278    /// propagated to its other replicas.
 279    Operation {
 280        operation: Operation,
 281        is_local: bool,
 282    },
 283    /// The buffer was edited.
 284    Edited,
 285    /// The buffer's `dirty` bit changed.
 286    DirtyChanged,
 287    /// The buffer was saved.
 288    Saved,
 289    /// The buffer's file was changed on disk.
 290    FileHandleChanged,
 291    /// The buffer was reloaded.
 292    Reloaded,
 293    /// The buffer is in need of a reload
 294    ReloadNeeded,
 295    /// The buffer's language was changed.
 296    LanguageChanged,
 297    /// The buffer's syntax trees were updated.
 298    Reparsed,
 299    /// The buffer's diagnostics were updated.
 300    DiagnosticsUpdated,
 301    /// The buffer gained or lost editing capabilities.
 302    CapabilityChanged,
 303    /// The buffer was explicitly requested to close.
 304    Closed,
 305    /// The buffer was discarded when closing.
 306    Discarded,
 307}
 308
 309/// The file associated with a buffer.
 310pub trait File: Send + Sync {
 311    /// Returns the [`LocalFile`] associated with this file, if the
 312    /// file is local.
 313    fn as_local(&self) -> Option<&dyn LocalFile>;
 314
 315    /// Returns whether this file is local.
 316    fn is_local(&self) -> bool {
 317        self.as_local().is_some()
 318    }
 319
 320    /// Returns whether the file is new, exists in storage, or has been deleted. Includes metadata
 321    /// only available in some states, such as modification time.
 322    fn disk_state(&self) -> DiskState;
 323
 324    /// Returns the path of this file relative to the worktree's root directory.
 325    fn path(&self) -> &Arc<Path>;
 326
 327    /// Returns the path of this file relative to the worktree's parent directory (this means it
 328    /// includes the name of the worktree's root folder).
 329    fn full_path(&self, cx: &App) -> PathBuf;
 330
 331    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 332    /// of its worktree, then this method will return the name of the worktree itself.
 333    fn file_name<'a>(&'a self, cx: &'a App) -> &'a OsStr;
 334
 335    /// Returns the id of the worktree to which this file belongs.
 336    ///
 337    /// This is needed for looking up project-specific settings.
 338    fn worktree_id(&self, cx: &App) -> WorktreeId;
 339
 340    /// Converts this file into an [`Any`] trait object.
 341    fn as_any(&self) -> &dyn Any;
 342
 343    /// Converts this file into a protobuf message.
 344    fn to_proto(&self, cx: &App) -> rpc::proto::File;
 345
 346    /// Return whether Zed considers this to be a private file.
 347    fn is_private(&self) -> bool;
 348}
 349
 350/// The file's storage status - whether it's stored (`Present`), and if so when it was last
 351/// modified. In the case where the file is not stored, it can be either `New` or `Deleted`. In the
 352/// UI these two states are distinguished. For example, the buffer tab does not display a deletion
 353/// indicator for new files.
 354#[derive(Copy, Clone, Debug, PartialEq)]
 355pub enum DiskState {
 356    /// File created in Zed that has not been saved.
 357    New,
 358    /// File present on the filesystem.
 359    Present { mtime: MTime },
 360    /// Deleted file that was previously present.
 361    Deleted,
 362}
 363
 364impl DiskState {
 365    /// Returns the file's last known modification time on disk.
 366    pub fn mtime(self) -> Option<MTime> {
 367        match self {
 368            DiskState::New => None,
 369            DiskState::Present { mtime } => Some(mtime),
 370            DiskState::Deleted => None,
 371        }
 372    }
 373
 374    pub fn exists(&self) -> bool {
 375        match self {
 376            DiskState::New => false,
 377            DiskState::Present { .. } => true,
 378            DiskState::Deleted => false,
 379        }
 380    }
 381}
 382
 383/// The file associated with a buffer, in the case where the file is on the local disk.
 384pub trait LocalFile: File {
 385    /// Returns the absolute path of this file
 386    fn abs_path(&self, cx: &App) -> PathBuf;
 387
 388    /// Loads the file contents from disk and returns them as a UTF-8 encoded string.
 389    fn load(&self, cx: &App) -> Task<Result<String>>;
 390
 391    /// Loads the file's contents from disk.
 392    fn load_bytes(&self, cx: &App) -> Task<Result<Vec<u8>>>;
 393}
 394
 395/// The auto-indent behavior associated with an editing operation.
 396/// For some editing operations, each affected line of text has its
 397/// indentation recomputed. For other operations, the entire block
 398/// of edited text is adjusted uniformly.
 399#[derive(Clone, Debug)]
 400pub enum AutoindentMode {
 401    /// Indent each line of inserted text.
 402    EachLine,
 403    /// Apply the same indentation adjustment to all of the lines
 404    /// in a given insertion.
 405    Block {
 406        /// The original indentation column of the first line of each
 407        /// insertion, if it has been copied.
 408        ///
 409        /// Knowing this makes it possible to preserve the relative indentation
 410        /// of every line in the insertion from when it was copied.
 411        ///
 412        /// If the original indent 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_indent_columns: Vec<Option<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 base_version: clock::Global,
 531    pub 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            reparse: None,
 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> + use<> {
 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(async move |this, cx| {
1309            let Some((new_mtime, new_text)) = this.update(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(cx, |this, cx| this.diff(new_text.clone(), cx))?
1320                .await;
1321            this.update(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.reparse.is_some()
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.reparse.is_some() {
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                self.reparse = None;
1501            }
1502            Err(parse_task) => {
1503                self.reparse = Some(cx.spawn(async move |this, cx| {
1504                    let new_syntax_map = parse_task.await;
1505                    this.update(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.reparse = None;
1520                        if parse_again {
1521                            this.reparse(cx);
1522                        }
1523                    })
1524                    .ok();
1525                }));
1526            }
1527        }
1528    }
1529
1530    fn did_finish_parsing(&mut self, syntax_snapshot: SyntaxSnapshot, cx: &mut Context<Self>) {
1531        self.was_changed();
1532        self.non_text_state_update_count += 1;
1533        self.syntax_map.lock().did_parse(syntax_snapshot);
1534        self.request_autoindent(cx);
1535        self.parse_status.0.send(ParseStatus::Idle).unwrap();
1536        cx.emit(BufferEvent::Reparsed);
1537        cx.notify();
1538    }
1539
1540    pub fn parse_status(&self) -> watch::Receiver<ParseStatus> {
1541        self.parse_status.1.clone()
1542    }
1543
1544    /// Assign to the buffer a set of diagnostics created by a given language server.
1545    pub fn update_diagnostics(
1546        &mut self,
1547        server_id: LanguageServerId,
1548        diagnostics: DiagnosticSet,
1549        cx: &mut Context<Self>,
1550    ) {
1551        let lamport_timestamp = self.text.lamport_clock.tick();
1552        let op = Operation::UpdateDiagnostics {
1553            server_id,
1554            diagnostics: diagnostics.iter().cloned().collect(),
1555            lamport_timestamp,
1556        };
1557        self.apply_diagnostic_update(server_id, diagnostics, lamport_timestamp, cx);
1558        self.send_operation(op, true, cx);
1559    }
1560
1561    pub fn get_diagnostics(&self, server_id: LanguageServerId) -> Option<&DiagnosticSet> {
1562        let Ok(idx) = self.diagnostics.binary_search_by_key(&server_id, |v| v.0) else {
1563            return None;
1564        };
1565        Some(&self.diagnostics[idx].1)
1566    }
1567
1568    fn request_autoindent(&mut self, cx: &mut Context<Self>) {
1569        if let Some(indent_sizes) = self.compute_autoindents() {
1570            let indent_sizes = cx.background_spawn(indent_sizes);
1571            match cx
1572                .background_executor()
1573                .block_with_timeout(Duration::from_micros(500), indent_sizes)
1574            {
1575                Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
1576                Err(indent_sizes) => {
1577                    self.pending_autoindent = Some(cx.spawn(async move |this, cx| {
1578                        let indent_sizes = indent_sizes.await;
1579                        this.update(cx, |this, cx| {
1580                            this.apply_autoindents(indent_sizes, cx);
1581                        })
1582                        .ok();
1583                    }));
1584                }
1585            }
1586        } else {
1587            self.autoindent_requests.clear();
1588        }
1589    }
1590
1591    fn compute_autoindents(
1592        &self,
1593    ) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>> + use<>> {
1594        let max_rows_between_yields = 100;
1595        let snapshot = self.snapshot();
1596        if snapshot.syntax.is_empty() || self.autoindent_requests.is_empty() {
1597            return None;
1598        }
1599
1600        let autoindent_requests = self.autoindent_requests.clone();
1601        Some(async move {
1602            let mut indent_sizes = BTreeMap::<u32, (IndentSize, bool)>::new();
1603            for request in autoindent_requests {
1604                // Resolve each edited range to its row in the current buffer and in the
1605                // buffer before this batch of edits.
1606                let mut row_ranges = Vec::new();
1607                let mut old_to_new_rows = BTreeMap::new();
1608                let mut language_indent_sizes_by_new_row = Vec::new();
1609                for entry in &request.entries {
1610                    let position = entry.range.start;
1611                    let new_row = position.to_point(&snapshot).row;
1612                    let new_end_row = entry.range.end.to_point(&snapshot).row + 1;
1613                    language_indent_sizes_by_new_row.push((new_row, entry.indent_size));
1614
1615                    if !entry.first_line_is_new {
1616                        let old_row = position.to_point(&request.before_edit).row;
1617                        old_to_new_rows.insert(old_row, new_row);
1618                    }
1619                    row_ranges.push((new_row..new_end_row, entry.original_indent_column));
1620                }
1621
1622                // Build a map containing the suggested indentation for each of the edited lines
1623                // with respect to the state of the buffer before these edits. This map is keyed
1624                // by the rows for these lines in the current state of the buffer.
1625                let mut old_suggestions = BTreeMap::<u32, (IndentSize, bool)>::default();
1626                let old_edited_ranges =
1627                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
1628                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1629                let mut language_indent_size = IndentSize::default();
1630                for old_edited_range in old_edited_ranges {
1631                    let suggestions = request
1632                        .before_edit
1633                        .suggest_autoindents(old_edited_range.clone())
1634                        .into_iter()
1635                        .flatten();
1636                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
1637                        if let Some(suggestion) = suggestion {
1638                            let new_row = *old_to_new_rows.get(&old_row).unwrap();
1639
1640                            // Find the indent size based on the language for this row.
1641                            while let Some((row, size)) = language_indent_sizes.peek() {
1642                                if *row > new_row {
1643                                    break;
1644                                }
1645                                language_indent_size = *size;
1646                                language_indent_sizes.next();
1647                            }
1648
1649                            let suggested_indent = old_to_new_rows
1650                                .get(&suggestion.basis_row)
1651                                .and_then(|from_row| {
1652                                    Some(old_suggestions.get(from_row).copied()?.0)
1653                                })
1654                                .unwrap_or_else(|| {
1655                                    request
1656                                        .before_edit
1657                                        .indent_size_for_line(suggestion.basis_row)
1658                                })
1659                                .with_delta(suggestion.delta, language_indent_size);
1660                            old_suggestions
1661                                .insert(new_row, (suggested_indent, suggestion.within_error));
1662                        }
1663                    }
1664                    yield_now().await;
1665                }
1666
1667                // Compute new suggestions for each line, but only include them in the result
1668                // if they differ from the old suggestion for that line.
1669                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1670                let mut language_indent_size = IndentSize::default();
1671                for (row_range, original_indent_column) in row_ranges {
1672                    let new_edited_row_range = if request.is_block_mode {
1673                        row_range.start..row_range.start + 1
1674                    } else {
1675                        row_range.clone()
1676                    };
1677
1678                    let suggestions = snapshot
1679                        .suggest_autoindents(new_edited_row_range.clone())
1680                        .into_iter()
1681                        .flatten();
1682                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
1683                        if let Some(suggestion) = suggestion {
1684                            // Find the indent size based on the language for this row.
1685                            while let Some((row, size)) = language_indent_sizes.peek() {
1686                                if *row > new_row {
1687                                    break;
1688                                }
1689                                language_indent_size = *size;
1690                                language_indent_sizes.next();
1691                            }
1692
1693                            let suggested_indent = indent_sizes
1694                                .get(&suggestion.basis_row)
1695                                .copied()
1696                                .map(|e| e.0)
1697                                .unwrap_or_else(|| {
1698                                    snapshot.indent_size_for_line(suggestion.basis_row)
1699                                })
1700                                .with_delta(suggestion.delta, language_indent_size);
1701
1702                            if old_suggestions.get(&new_row).map_or(
1703                                true,
1704                                |(old_indentation, was_within_error)| {
1705                                    suggested_indent != *old_indentation
1706                                        && (!suggestion.within_error || *was_within_error)
1707                                },
1708                            ) {
1709                                indent_sizes.insert(
1710                                    new_row,
1711                                    (suggested_indent, request.ignore_empty_lines),
1712                                );
1713                            }
1714                        }
1715                    }
1716
1717                    if let (true, Some(original_indent_column)) =
1718                        (request.is_block_mode, original_indent_column)
1719                    {
1720                        let new_indent =
1721                            if let Some((indent, _)) = indent_sizes.get(&row_range.start) {
1722                                *indent
1723                            } else {
1724                                snapshot.indent_size_for_line(row_range.start)
1725                            };
1726                        let delta = new_indent.len as i64 - original_indent_column as i64;
1727                        if delta != 0 {
1728                            for row in row_range.skip(1) {
1729                                indent_sizes.entry(row).or_insert_with(|| {
1730                                    let mut size = snapshot.indent_size_for_line(row);
1731                                    if size.kind == new_indent.kind {
1732                                        match delta.cmp(&0) {
1733                                            Ordering::Greater => size.len += delta as u32,
1734                                            Ordering::Less => {
1735                                                size.len = size.len.saturating_sub(-delta as u32)
1736                                            }
1737                                            Ordering::Equal => {}
1738                                        }
1739                                    }
1740                                    (size, request.ignore_empty_lines)
1741                                });
1742                            }
1743                        }
1744                    }
1745
1746                    yield_now().await;
1747                }
1748            }
1749
1750            indent_sizes
1751                .into_iter()
1752                .filter_map(|(row, (indent, ignore_empty_lines))| {
1753                    if ignore_empty_lines && snapshot.line_len(row) == 0 {
1754                        None
1755                    } else {
1756                        Some((row, indent))
1757                    }
1758                })
1759                .collect()
1760        })
1761    }
1762
1763    fn apply_autoindents(
1764        &mut self,
1765        indent_sizes: BTreeMap<u32, IndentSize>,
1766        cx: &mut Context<Self>,
1767    ) {
1768        self.autoindent_requests.clear();
1769
1770        let edits: Vec<_> = indent_sizes
1771            .into_iter()
1772            .filter_map(|(row, indent_size)| {
1773                let current_size = indent_size_for_line(self, row);
1774                Self::edit_for_indent_size_adjustment(row, current_size, indent_size)
1775            })
1776            .collect();
1777
1778        let preserve_preview = self.preserve_preview();
1779        self.edit(edits, None, cx);
1780        if preserve_preview {
1781            self.refresh_preview();
1782        }
1783    }
1784
1785    /// Create a minimal edit that will cause the given row to be indented
1786    /// with the given size. After applying this edit, the length of the line
1787    /// will always be at least `new_size.len`.
1788    pub fn edit_for_indent_size_adjustment(
1789        row: u32,
1790        current_size: IndentSize,
1791        new_size: IndentSize,
1792    ) -> Option<(Range<Point>, String)> {
1793        if new_size.kind == current_size.kind {
1794            match new_size.len.cmp(&current_size.len) {
1795                Ordering::Greater => {
1796                    let point = Point::new(row, 0);
1797                    Some((
1798                        point..point,
1799                        iter::repeat(new_size.char())
1800                            .take((new_size.len - current_size.len) as usize)
1801                            .collect::<String>(),
1802                    ))
1803                }
1804
1805                Ordering::Less => Some((
1806                    Point::new(row, 0)..Point::new(row, current_size.len - new_size.len),
1807                    String::new(),
1808                )),
1809
1810                Ordering::Equal => None,
1811            }
1812        } else {
1813            Some((
1814                Point::new(row, 0)..Point::new(row, current_size.len),
1815                iter::repeat(new_size.char())
1816                    .take(new_size.len as usize)
1817                    .collect::<String>(),
1818            ))
1819        }
1820    }
1821
1822    /// Spawns a background task that asynchronously computes a `Diff` between the buffer's text
1823    /// and the given new text.
1824    pub fn diff(&self, mut new_text: String, cx: &App) -> Task<Diff> {
1825        let old_text = self.as_rope().clone();
1826        let base_version = self.version();
1827        cx.background_executor()
1828            .spawn_labeled(*BUFFER_DIFF_TASK, async move {
1829                let old_text = old_text.to_string();
1830                let line_ending = LineEnding::detect(&new_text);
1831                LineEnding::normalize(&mut new_text);
1832                let edits = text_diff(&old_text, &new_text);
1833                Diff {
1834                    base_version,
1835                    line_ending,
1836                    edits,
1837                }
1838            })
1839    }
1840
1841    /// Spawns a background task that searches the buffer for any whitespace
1842    /// at the ends of a lines, and returns a `Diff` that removes that whitespace.
1843    pub fn remove_trailing_whitespace(&self, cx: &App) -> Task<Diff> {
1844        let old_text = self.as_rope().clone();
1845        let line_ending = self.line_ending();
1846        let base_version = self.version();
1847        cx.background_spawn(async move {
1848            let ranges = trailing_whitespace_ranges(&old_text);
1849            let empty = Arc::<str>::from("");
1850            Diff {
1851                base_version,
1852                line_ending,
1853                edits: ranges
1854                    .into_iter()
1855                    .map(|range| (range, empty.clone()))
1856                    .collect(),
1857            }
1858        })
1859    }
1860
1861    /// Ensures that the buffer ends with a single newline character, and
1862    /// no other whitespace.
1863    pub fn ensure_final_newline(&mut self, cx: &mut Context<Self>) {
1864        let len = self.len();
1865        let mut offset = len;
1866        for chunk in self.as_rope().reversed_chunks_in_range(0..len) {
1867            let non_whitespace_len = chunk
1868                .trim_end_matches(|c: char| c.is_ascii_whitespace())
1869                .len();
1870            offset -= chunk.len();
1871            offset += non_whitespace_len;
1872            if non_whitespace_len != 0 {
1873                if offset == len - 1 && chunk.get(non_whitespace_len..) == Some("\n") {
1874                    return;
1875                }
1876                break;
1877            }
1878        }
1879        self.edit([(offset..len, "\n")], None, cx);
1880    }
1881
1882    /// Applies a diff to the buffer. If the buffer has changed since the given diff was
1883    /// calculated, then adjust the diff to account for those changes, and discard any
1884    /// parts of the diff that conflict with those changes.
1885    pub fn apply_diff(&mut self, diff: Diff, cx: &mut Context<Self>) -> Option<TransactionId> {
1886        let snapshot = self.snapshot();
1887        let mut edits_since = snapshot.edits_since::<usize>(&diff.base_version).peekable();
1888        let mut delta = 0;
1889        let adjusted_edits = diff.edits.into_iter().filter_map(|(range, new_text)| {
1890            while let Some(edit_since) = edits_since.peek() {
1891                // If the edit occurs after a diff hunk, then it does not
1892                // affect that hunk.
1893                if edit_since.old.start > range.end {
1894                    break;
1895                }
1896                // If the edit precedes the diff hunk, then adjust the hunk
1897                // to reflect the edit.
1898                else if edit_since.old.end < range.start {
1899                    delta += edit_since.new_len() as i64 - edit_since.old_len() as i64;
1900                    edits_since.next();
1901                }
1902                // If the edit intersects a diff hunk, then discard that hunk.
1903                else {
1904                    return None;
1905                }
1906            }
1907
1908            let start = (range.start as i64 + delta) as usize;
1909            let end = (range.end as i64 + delta) as usize;
1910            Some((start..end, new_text))
1911        });
1912
1913        self.start_transaction();
1914        self.text.set_line_ending(diff.line_ending);
1915        self.edit(adjusted_edits, None, cx);
1916        self.end_transaction(cx)
1917    }
1918
1919    fn has_unsaved_edits(&self) -> bool {
1920        let (last_version, has_unsaved_edits) = self.has_unsaved_edits.take();
1921
1922        if last_version == self.version {
1923            self.has_unsaved_edits
1924                .set((last_version, has_unsaved_edits));
1925            return has_unsaved_edits;
1926        }
1927
1928        let has_edits = self.has_edits_since(&self.saved_version);
1929        self.has_unsaved_edits
1930            .set((self.version.clone(), has_edits));
1931        has_edits
1932    }
1933
1934    /// Checks if the buffer has unsaved changes.
1935    pub fn is_dirty(&self) -> bool {
1936        if self.capability == Capability::ReadOnly {
1937            return false;
1938        }
1939        if self.has_conflict {
1940            return true;
1941        }
1942        match self.file.as_ref().map(|f| f.disk_state()) {
1943            Some(DiskState::New) | Some(DiskState::Deleted) => {
1944                !self.is_empty() && self.has_unsaved_edits()
1945            }
1946            _ => self.has_unsaved_edits(),
1947        }
1948    }
1949
1950    /// Checks if the buffer and its file have both changed since the buffer
1951    /// was last saved or reloaded.
1952    pub fn has_conflict(&self) -> bool {
1953        if self.has_conflict {
1954            return true;
1955        }
1956        let Some(file) = self.file.as_ref() else {
1957            return false;
1958        };
1959        match file.disk_state() {
1960            DiskState::New => false,
1961            DiskState::Present { mtime } => match self.saved_mtime {
1962                Some(saved_mtime) => {
1963                    mtime.bad_is_greater_than(saved_mtime) && self.has_unsaved_edits()
1964                }
1965                None => true,
1966            },
1967            DiskState::Deleted => false,
1968        }
1969    }
1970
1971    /// Gets a [`Subscription`] that tracks all of the changes to the buffer's text.
1972    pub fn subscribe(&mut self) -> Subscription {
1973        self.text.subscribe()
1974    }
1975
1976    /// Adds a bit to the list of bits that are set when the buffer's text changes.
1977    ///
1978    /// This allows downstream code to check if the buffer's text has changed without
1979    /// waiting for an effect cycle, which would be required if using eents.
1980    pub fn record_changes(&mut self, bit: rc::Weak<Cell<bool>>) {
1981        if let Err(ix) = self
1982            .change_bits
1983            .binary_search_by_key(&rc::Weak::as_ptr(&bit), rc::Weak::as_ptr)
1984        {
1985            self.change_bits.insert(ix, bit);
1986        }
1987    }
1988
1989    fn was_changed(&mut self) {
1990        self.change_bits.retain(|change_bit| {
1991            change_bit.upgrade().map_or(false, |bit| {
1992                bit.replace(true);
1993                true
1994            })
1995        });
1996    }
1997
1998    /// Starts a transaction, if one is not already in-progress. When undoing or
1999    /// redoing edits, all of the edits performed within a transaction are undone
2000    /// or redone together.
2001    pub fn start_transaction(&mut self) -> Option<TransactionId> {
2002        self.start_transaction_at(Instant::now())
2003    }
2004
2005    /// Starts a transaction, providing the current time. Subsequent transactions
2006    /// that occur within a short period of time will be grouped together. This
2007    /// is controlled by the buffer's undo grouping duration.
2008    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
2009        self.transaction_depth += 1;
2010        if self.was_dirty_before_starting_transaction.is_none() {
2011            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
2012        }
2013        self.text.start_transaction_at(now)
2014    }
2015
2016    /// Terminates the current transaction, if this is the outermost transaction.
2017    pub fn end_transaction(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2018        self.end_transaction_at(Instant::now(), cx)
2019    }
2020
2021    /// Terminates the current transaction, providing the current time. Subsequent transactions
2022    /// that occur within a short period of time will be grouped together. This
2023    /// is controlled by the buffer's undo grouping duration.
2024    pub fn end_transaction_at(
2025        &mut self,
2026        now: Instant,
2027        cx: &mut Context<Self>,
2028    ) -> Option<TransactionId> {
2029        assert!(self.transaction_depth > 0);
2030        self.transaction_depth -= 1;
2031        let was_dirty = if self.transaction_depth == 0 {
2032            self.was_dirty_before_starting_transaction.take().unwrap()
2033        } else {
2034            false
2035        };
2036        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
2037            self.did_edit(&start_version, was_dirty, cx);
2038            Some(transaction_id)
2039        } else {
2040            None
2041        }
2042    }
2043
2044    /// Manually add a transaction to the buffer's undo history.
2045    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
2046        self.text.push_transaction(transaction, now);
2047    }
2048
2049    /// Prevent the last transaction from being grouped with any subsequent transactions,
2050    /// even if they occur with the buffer's undo grouping duration.
2051    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
2052        self.text.finalize_last_transaction()
2053    }
2054
2055    /// Manually group all changes since a given transaction.
2056    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
2057        self.text.group_until_transaction(transaction_id);
2058    }
2059
2060    /// Manually remove a transaction from the buffer's undo history
2061    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
2062        self.text.forget_transaction(transaction_id);
2063    }
2064
2065    /// Manually merge two adjacent transactions in the buffer's undo history.
2066    pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
2067        self.text.merge_transactions(transaction, destination);
2068    }
2069
2070    /// Waits for the buffer to receive operations with the given timestamps.
2071    pub fn wait_for_edits<It: IntoIterator<Item = clock::Lamport>>(
2072        &mut self,
2073        edit_ids: It,
2074    ) -> impl Future<Output = Result<()>> + use<It> {
2075        self.text.wait_for_edits(edit_ids)
2076    }
2077
2078    /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
2079    pub fn wait_for_anchors<It: IntoIterator<Item = Anchor>>(
2080        &mut self,
2081        anchors: It,
2082    ) -> impl 'static + Future<Output = Result<()>> + use<It> {
2083        self.text.wait_for_anchors(anchors)
2084    }
2085
2086    /// Waits for the buffer to receive operations up to the given version.
2087    pub fn wait_for_version(
2088        &mut self,
2089        version: clock::Global,
2090    ) -> impl Future<Output = Result<()>> + use<> {
2091        self.text.wait_for_version(version)
2092    }
2093
2094    /// Forces all futures returned by [`Buffer::wait_for_version`], [`Buffer::wait_for_edits`], or
2095    /// [`Buffer::wait_for_version`] to resolve with an error.
2096    pub fn give_up_waiting(&mut self) {
2097        self.text.give_up_waiting();
2098    }
2099
2100    /// Stores a set of selections that should be broadcasted to all of the buffer's replicas.
2101    pub fn set_active_selections(
2102        &mut self,
2103        selections: Arc<[Selection<Anchor>]>,
2104        line_mode: bool,
2105        cursor_shape: CursorShape,
2106        cx: &mut Context<Self>,
2107    ) {
2108        let lamport_timestamp = self.text.lamport_clock.tick();
2109        self.remote_selections.insert(
2110            self.text.replica_id(),
2111            SelectionSet {
2112                selections: selections.clone(),
2113                lamport_timestamp,
2114                line_mode,
2115                cursor_shape,
2116            },
2117        );
2118        self.send_operation(
2119            Operation::UpdateSelections {
2120                selections,
2121                line_mode,
2122                lamport_timestamp,
2123                cursor_shape,
2124            },
2125            true,
2126            cx,
2127        );
2128        self.non_text_state_update_count += 1;
2129        cx.notify();
2130    }
2131
2132    /// Clears the selections, so that other replicas of the buffer do not see any selections for
2133    /// this replica.
2134    pub fn remove_active_selections(&mut self, cx: &mut Context<Self>) {
2135        if self
2136            .remote_selections
2137            .get(&self.text.replica_id())
2138            .map_or(true, |set| !set.selections.is_empty())
2139        {
2140            self.set_active_selections(Arc::default(), false, Default::default(), cx);
2141        }
2142    }
2143
2144    /// Replaces the buffer's entire text.
2145    pub fn set_text<T>(&mut self, text: T, cx: &mut Context<Self>) -> Option<clock::Lamport>
2146    where
2147        T: Into<Arc<str>>,
2148    {
2149        self.autoindent_requests.clear();
2150        self.edit([(0..self.len(), text)], None, cx)
2151    }
2152
2153    /// Applies the given edits to the buffer. Each edit is specified as a range of text to
2154    /// delete, and a string of text to insert at that location.
2155    ///
2156    /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
2157    /// request for the edited ranges, which will be processed when the buffer finishes
2158    /// parsing.
2159    ///
2160    /// Parsing takes place at the end of a transaction, and may compute synchronously
2161    /// or asynchronously, depending on the changes.
2162    pub fn edit<I, S, T>(
2163        &mut self,
2164        edits_iter: I,
2165        autoindent_mode: Option<AutoindentMode>,
2166        cx: &mut Context<Self>,
2167    ) -> Option<clock::Lamport>
2168    where
2169        I: IntoIterator<Item = (Range<S>, T)>,
2170        S: ToOffset,
2171        T: Into<Arc<str>>,
2172    {
2173        // Skip invalid edits and coalesce contiguous ones.
2174        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
2175
2176        for (range, new_text) in edits_iter {
2177            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2178
2179            if range.start > range.end {
2180                mem::swap(&mut range.start, &mut range.end);
2181            }
2182            let new_text = new_text.into();
2183            if !new_text.is_empty() || !range.is_empty() {
2184                if let Some((prev_range, prev_text)) = edits.last_mut() {
2185                    if prev_range.end >= range.start {
2186                        prev_range.end = cmp::max(prev_range.end, range.end);
2187                        *prev_text = format!("{prev_text}{new_text}").into();
2188                    } else {
2189                        edits.push((range, new_text));
2190                    }
2191                } else {
2192                    edits.push((range, new_text));
2193                }
2194            }
2195        }
2196        if edits.is_empty() {
2197            return None;
2198        }
2199
2200        self.start_transaction();
2201        self.pending_autoindent.take();
2202        let autoindent_request = autoindent_mode
2203            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
2204
2205        let edit_operation = self.text.edit(edits.iter().cloned());
2206        let edit_id = edit_operation.timestamp();
2207
2208        if let Some((before_edit, mode)) = autoindent_request {
2209            let mut delta = 0isize;
2210            let entries = edits
2211                .into_iter()
2212                .enumerate()
2213                .zip(&edit_operation.as_edit().unwrap().new_text)
2214                .map(|((ix, (range, _)), new_text)| {
2215                    let new_text_length = new_text.len();
2216                    let old_start = range.start.to_point(&before_edit);
2217                    let new_start = (delta + range.start as isize) as usize;
2218                    let range_len = range.end - range.start;
2219                    delta += new_text_length as isize - range_len as isize;
2220
2221                    // Decide what range of the insertion to auto-indent, and whether
2222                    // the first line of the insertion should be considered a newly-inserted line
2223                    // or an edit to an existing line.
2224                    let mut range_of_insertion_to_indent = 0..new_text_length;
2225                    let mut first_line_is_new = true;
2226
2227                    let old_line_start = before_edit.indent_size_for_line(old_start.row).len;
2228                    let old_line_end = before_edit.line_len(old_start.row);
2229
2230                    if old_start.column > old_line_start {
2231                        first_line_is_new = false;
2232                    }
2233
2234                    if !new_text.contains('\n')
2235                        && (old_start.column + (range_len as u32) < old_line_end
2236                            || old_line_end == old_line_start)
2237                    {
2238                        first_line_is_new = false;
2239                    }
2240
2241                    // When inserting text starting with a newline, avoid auto-indenting the
2242                    // previous line.
2243                    if new_text.starts_with('\n') {
2244                        range_of_insertion_to_indent.start += 1;
2245                        first_line_is_new = true;
2246                    }
2247
2248                    let mut original_indent_column = None;
2249                    if let AutoindentMode::Block {
2250                        original_indent_columns,
2251                    } = &mode
2252                    {
2253                        original_indent_column = Some(
2254                            original_indent_columns
2255                                .get(ix)
2256                                .copied()
2257                                .flatten()
2258                                .unwrap_or_else(|| {
2259                                    indent_size_for_text(
2260                                        new_text[range_of_insertion_to_indent.clone()].chars(),
2261                                    )
2262                                    .len
2263                                }),
2264                        );
2265
2266                        // Avoid auto-indenting the line after the edit.
2267                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
2268                            range_of_insertion_to_indent.end -= 1;
2269                        }
2270                    }
2271
2272                    AutoindentRequestEntry {
2273                        first_line_is_new,
2274                        original_indent_column,
2275                        indent_size: before_edit.language_indent_size_at(range.start, cx),
2276                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
2277                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
2278                    }
2279                })
2280                .collect();
2281
2282            self.autoindent_requests.push(Arc::new(AutoindentRequest {
2283                before_edit,
2284                entries,
2285                is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
2286                ignore_empty_lines: false,
2287            }));
2288        }
2289
2290        self.end_transaction(cx);
2291        self.send_operation(Operation::Buffer(edit_operation), true, cx);
2292        Some(edit_id)
2293    }
2294
2295    fn did_edit(&mut self, old_version: &clock::Global, was_dirty: bool, cx: &mut Context<Self>) {
2296        self.was_changed();
2297
2298        if self.edits_since::<usize>(old_version).next().is_none() {
2299            return;
2300        }
2301
2302        self.reparse(cx);
2303        cx.emit(BufferEvent::Edited);
2304        if was_dirty != self.is_dirty() {
2305            cx.emit(BufferEvent::DirtyChanged);
2306        }
2307        cx.notify();
2308    }
2309
2310    pub fn autoindent_ranges<I, T>(&mut self, ranges: I, cx: &mut Context<Self>)
2311    where
2312        I: IntoIterator<Item = Range<T>>,
2313        T: ToOffset + Copy,
2314    {
2315        let before_edit = self.snapshot();
2316        let entries = ranges
2317            .into_iter()
2318            .map(|range| AutoindentRequestEntry {
2319                range: before_edit.anchor_before(range.start)..before_edit.anchor_after(range.end),
2320                first_line_is_new: true,
2321                indent_size: before_edit.language_indent_size_at(range.start, cx),
2322                original_indent_column: None,
2323            })
2324            .collect();
2325        self.autoindent_requests.push(Arc::new(AutoindentRequest {
2326            before_edit,
2327            entries,
2328            is_block_mode: false,
2329            ignore_empty_lines: true,
2330        }));
2331        self.request_autoindent(cx);
2332    }
2333
2334    // Inserts newlines at the given position to create an empty line, returning the start of the new line.
2335    // You can also request the insertion of empty lines above and below the line starting at the returned point.
2336    pub fn insert_empty_line(
2337        &mut self,
2338        position: impl ToPoint,
2339        space_above: bool,
2340        space_below: bool,
2341        cx: &mut Context<Self>,
2342    ) -> Point {
2343        let mut position = position.to_point(self);
2344
2345        self.start_transaction();
2346
2347        self.edit(
2348            [(position..position, "\n")],
2349            Some(AutoindentMode::EachLine),
2350            cx,
2351        );
2352
2353        if position.column > 0 {
2354            position += Point::new(1, 0);
2355        }
2356
2357        if !self.is_line_blank(position.row) {
2358            self.edit(
2359                [(position..position, "\n")],
2360                Some(AutoindentMode::EachLine),
2361                cx,
2362            );
2363        }
2364
2365        if space_above && position.row > 0 && !self.is_line_blank(position.row - 1) {
2366            self.edit(
2367                [(position..position, "\n")],
2368                Some(AutoindentMode::EachLine),
2369                cx,
2370            );
2371            position.row += 1;
2372        }
2373
2374        if space_below
2375            && (position.row == self.max_point().row || !self.is_line_blank(position.row + 1))
2376        {
2377            self.edit(
2378                [(position..position, "\n")],
2379                Some(AutoindentMode::EachLine),
2380                cx,
2381            );
2382        }
2383
2384        self.end_transaction(cx);
2385
2386        position
2387    }
2388
2389    /// Applies the given remote operations to the buffer.
2390    pub fn apply_ops<I: IntoIterator<Item = Operation>>(&mut self, ops: I, cx: &mut Context<Self>) {
2391        self.pending_autoindent.take();
2392        let was_dirty = self.is_dirty();
2393        let old_version = self.version.clone();
2394        let mut deferred_ops = Vec::new();
2395        let buffer_ops = ops
2396            .into_iter()
2397            .filter_map(|op| match op {
2398                Operation::Buffer(op) => Some(op),
2399                _ => {
2400                    if self.can_apply_op(&op) {
2401                        self.apply_op(op, cx);
2402                    } else {
2403                        deferred_ops.push(op);
2404                    }
2405                    None
2406                }
2407            })
2408            .collect::<Vec<_>>();
2409        for operation in buffer_ops.iter() {
2410            self.send_operation(Operation::Buffer(operation.clone()), false, cx);
2411        }
2412        self.text.apply_ops(buffer_ops);
2413        self.deferred_ops.insert(deferred_ops);
2414        self.flush_deferred_ops(cx);
2415        self.did_edit(&old_version, was_dirty, cx);
2416        // Notify independently of whether the buffer was edited as the operations could include a
2417        // selection update.
2418        cx.notify();
2419    }
2420
2421    fn flush_deferred_ops(&mut self, cx: &mut Context<Self>) {
2422        let mut deferred_ops = Vec::new();
2423        for op in self.deferred_ops.drain().iter().cloned() {
2424            if self.can_apply_op(&op) {
2425                self.apply_op(op, cx);
2426            } else {
2427                deferred_ops.push(op);
2428            }
2429        }
2430        self.deferred_ops.insert(deferred_ops);
2431    }
2432
2433    pub fn has_deferred_ops(&self) -> bool {
2434        !self.deferred_ops.is_empty() || self.text.has_deferred_ops()
2435    }
2436
2437    fn can_apply_op(&self, operation: &Operation) -> bool {
2438        match operation {
2439            Operation::Buffer(_) => {
2440                unreachable!("buffer operations should never be applied at this layer")
2441            }
2442            Operation::UpdateDiagnostics {
2443                diagnostics: diagnostic_set,
2444                ..
2445            } => diagnostic_set.iter().all(|diagnostic| {
2446                self.text.can_resolve(&diagnostic.range.start)
2447                    && self.text.can_resolve(&diagnostic.range.end)
2448            }),
2449            Operation::UpdateSelections { selections, .. } => selections
2450                .iter()
2451                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
2452            Operation::UpdateCompletionTriggers { .. } => true,
2453        }
2454    }
2455
2456    fn apply_op(&mut self, operation: Operation, cx: &mut Context<Self>) {
2457        match operation {
2458            Operation::Buffer(_) => {
2459                unreachable!("buffer operations should never be applied at this layer")
2460            }
2461            Operation::UpdateDiagnostics {
2462                server_id,
2463                diagnostics: diagnostic_set,
2464                lamport_timestamp,
2465            } => {
2466                let snapshot = self.snapshot();
2467                self.apply_diagnostic_update(
2468                    server_id,
2469                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
2470                    lamport_timestamp,
2471                    cx,
2472                );
2473            }
2474            Operation::UpdateSelections {
2475                selections,
2476                lamport_timestamp,
2477                line_mode,
2478                cursor_shape,
2479            } => {
2480                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
2481                    if set.lamport_timestamp > lamport_timestamp {
2482                        return;
2483                    }
2484                }
2485
2486                self.remote_selections.insert(
2487                    lamport_timestamp.replica_id,
2488                    SelectionSet {
2489                        selections,
2490                        lamport_timestamp,
2491                        line_mode,
2492                        cursor_shape,
2493                    },
2494                );
2495                self.text.lamport_clock.observe(lamport_timestamp);
2496                self.non_text_state_update_count += 1;
2497            }
2498            Operation::UpdateCompletionTriggers {
2499                triggers,
2500                lamport_timestamp,
2501                server_id,
2502            } => {
2503                if triggers.is_empty() {
2504                    self.completion_triggers_per_language_server
2505                        .remove(&server_id);
2506                    self.completion_triggers = self
2507                        .completion_triggers_per_language_server
2508                        .values()
2509                        .flat_map(|triggers| triggers.into_iter().cloned())
2510                        .collect();
2511                } else {
2512                    self.completion_triggers_per_language_server
2513                        .insert(server_id, triggers.iter().cloned().collect());
2514                    self.completion_triggers.extend(triggers);
2515                }
2516                self.text.lamport_clock.observe(lamport_timestamp);
2517            }
2518        }
2519    }
2520
2521    fn apply_diagnostic_update(
2522        &mut self,
2523        server_id: LanguageServerId,
2524        diagnostics: DiagnosticSet,
2525        lamport_timestamp: clock::Lamport,
2526        cx: &mut Context<Self>,
2527    ) {
2528        if lamport_timestamp > self.diagnostics_timestamp {
2529            let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
2530            if diagnostics.is_empty() {
2531                if let Ok(ix) = ix {
2532                    self.diagnostics.remove(ix);
2533                }
2534            } else {
2535                match ix {
2536                    Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
2537                    Ok(ix) => self.diagnostics[ix].1 = diagnostics,
2538                };
2539            }
2540            self.diagnostics_timestamp = lamport_timestamp;
2541            self.non_text_state_update_count += 1;
2542            self.text.lamport_clock.observe(lamport_timestamp);
2543            cx.notify();
2544            cx.emit(BufferEvent::DiagnosticsUpdated);
2545        }
2546    }
2547
2548    fn send_operation(&mut self, operation: Operation, is_local: bool, cx: &mut Context<Self>) {
2549        self.was_changed();
2550        cx.emit(BufferEvent::Operation {
2551            operation,
2552            is_local,
2553        });
2554    }
2555
2556    /// Removes the selections for a given peer.
2557    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut Context<Self>) {
2558        self.remote_selections.remove(&replica_id);
2559        cx.notify();
2560    }
2561
2562    /// Undoes the most recent transaction.
2563    pub fn undo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2564        let was_dirty = self.is_dirty();
2565        let old_version = self.version.clone();
2566
2567        if let Some((transaction_id, operation)) = self.text.undo() {
2568            self.send_operation(Operation::Buffer(operation), true, cx);
2569            self.did_edit(&old_version, was_dirty, cx);
2570            Some(transaction_id)
2571        } else {
2572            None
2573        }
2574    }
2575
2576    /// Manually undoes a specific transaction in the buffer's undo history.
2577    pub fn undo_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        if let Some(operation) = self.text.undo_transaction(transaction_id) {
2585            self.send_operation(Operation::Buffer(operation), true, cx);
2586            self.did_edit(&old_version, was_dirty, cx);
2587            true
2588        } else {
2589            false
2590        }
2591    }
2592
2593    /// Manually undoes all changes after a given transaction in the buffer's undo history.
2594    pub fn undo_to_transaction(
2595        &mut self,
2596        transaction_id: TransactionId,
2597        cx: &mut Context<Self>,
2598    ) -> bool {
2599        let was_dirty = self.is_dirty();
2600        let old_version = self.version.clone();
2601
2602        let operations = self.text.undo_to_transaction(transaction_id);
2603        let undone = !operations.is_empty();
2604        for operation in operations {
2605            self.send_operation(Operation::Buffer(operation), true, cx);
2606        }
2607        if undone {
2608            self.did_edit(&old_version, was_dirty, cx)
2609        }
2610        undone
2611    }
2612
2613    pub fn undo_operations(&mut self, counts: HashMap<Lamport, u32>, cx: &mut Context<Buffer>) {
2614        let was_dirty = self.is_dirty();
2615        let operation = self.text.undo_operations(counts);
2616        let old_version = self.version.clone();
2617        self.send_operation(Operation::Buffer(operation), true, cx);
2618        self.did_edit(&old_version, was_dirty, cx);
2619    }
2620
2621    /// Manually redoes a specific transaction in the buffer's redo history.
2622    pub fn redo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2623        let was_dirty = self.is_dirty();
2624        let old_version = self.version.clone();
2625
2626        if let Some((transaction_id, operation)) = self.text.redo() {
2627            self.send_operation(Operation::Buffer(operation), true, cx);
2628            self.did_edit(&old_version, was_dirty, cx);
2629            Some(transaction_id)
2630        } else {
2631            None
2632        }
2633    }
2634
2635    /// Manually undoes all changes until a given transaction in the buffer's redo history.
2636    pub fn redo_to_transaction(
2637        &mut self,
2638        transaction_id: TransactionId,
2639        cx: &mut Context<Self>,
2640    ) -> bool {
2641        let was_dirty = self.is_dirty();
2642        let old_version = self.version.clone();
2643
2644        let operations = self.text.redo_to_transaction(transaction_id);
2645        let redone = !operations.is_empty();
2646        for operation in operations {
2647            self.send_operation(Operation::Buffer(operation), true, cx);
2648        }
2649        if redone {
2650            self.did_edit(&old_version, was_dirty, cx)
2651        }
2652        redone
2653    }
2654
2655    /// Override current completion triggers with the user-provided completion triggers.
2656    pub fn set_completion_triggers(
2657        &mut self,
2658        server_id: LanguageServerId,
2659        triggers: BTreeSet<String>,
2660        cx: &mut Context<Self>,
2661    ) {
2662        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2663        if triggers.is_empty() {
2664            self.completion_triggers_per_language_server
2665                .remove(&server_id);
2666            self.completion_triggers = self
2667                .completion_triggers_per_language_server
2668                .values()
2669                .flat_map(|triggers| triggers.into_iter().cloned())
2670                .collect();
2671        } else {
2672            self.completion_triggers_per_language_server
2673                .insert(server_id, triggers.clone());
2674            self.completion_triggers.extend(triggers.iter().cloned());
2675        }
2676        self.send_operation(
2677            Operation::UpdateCompletionTriggers {
2678                triggers: triggers.iter().cloned().collect(),
2679                lamport_timestamp: self.completion_triggers_timestamp,
2680                server_id,
2681            },
2682            true,
2683            cx,
2684        );
2685        cx.notify();
2686    }
2687
2688    /// Returns a list of strings which trigger a completion menu for this language.
2689    /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2690    pub fn completion_triggers(&self) -> &BTreeSet<String> {
2691        &self.completion_triggers
2692    }
2693
2694    /// Call this directly after performing edits to prevent the preview tab
2695    /// from being dismissed by those edits. It causes `should_dismiss_preview`
2696    /// to return false until there are additional edits.
2697    pub fn refresh_preview(&mut self) {
2698        self.preview_version = self.version.clone();
2699    }
2700
2701    /// Whether we should preserve the preview status of a tab containing this buffer.
2702    pub fn preserve_preview(&self) -> bool {
2703        !self.has_edits_since(&self.preview_version)
2704    }
2705}
2706
2707#[doc(hidden)]
2708#[cfg(any(test, feature = "test-support"))]
2709impl Buffer {
2710    pub fn edit_via_marked_text(
2711        &mut self,
2712        marked_string: &str,
2713        autoindent_mode: Option<AutoindentMode>,
2714        cx: &mut Context<Self>,
2715    ) {
2716        let edits = self.edits_for_marked_text(marked_string);
2717        self.edit(edits, autoindent_mode, cx);
2718    }
2719
2720    pub fn set_group_interval(&mut self, group_interval: Duration) {
2721        self.text.set_group_interval(group_interval);
2722    }
2723
2724    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize, cx: &mut Context<Self>)
2725    where
2726        T: rand::Rng,
2727    {
2728        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2729        let mut last_end = None;
2730        for _ in 0..old_range_count {
2731            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2732                break;
2733            }
2734
2735            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2736            let mut range = self.random_byte_range(new_start, rng);
2737            if rng.gen_bool(0.2) {
2738                mem::swap(&mut range.start, &mut range.end);
2739            }
2740            last_end = Some(range.end);
2741
2742            let new_text_len = rng.gen_range(0..10);
2743            let mut new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2744            new_text = new_text.to_uppercase();
2745
2746            edits.push((range, new_text));
2747        }
2748        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2749        self.edit(edits, None, cx);
2750    }
2751
2752    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut Context<Self>) {
2753        let was_dirty = self.is_dirty();
2754        let old_version = self.version.clone();
2755
2756        let ops = self.text.randomly_undo_redo(rng);
2757        if !ops.is_empty() {
2758            for op in ops {
2759                self.send_operation(Operation::Buffer(op), true, cx);
2760                self.did_edit(&old_version, was_dirty, cx);
2761            }
2762        }
2763    }
2764}
2765
2766impl EventEmitter<BufferEvent> for Buffer {}
2767
2768impl Deref for Buffer {
2769    type Target = TextBuffer;
2770
2771    fn deref(&self) -> &Self::Target {
2772        &self.text
2773    }
2774}
2775
2776impl BufferSnapshot {
2777    /// Returns [`IndentSize`] for a given line that respects user settings and
2778    /// language preferences.
2779    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2780        indent_size_for_line(self, row)
2781    }
2782
2783    /// Returns [`IndentSize`] for a given position that respects user settings
2784    /// and language preferences.
2785    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &App) -> IndentSize {
2786        let settings = language_settings(
2787            self.language_at(position).map(|l| l.name()),
2788            self.file(),
2789            cx,
2790        );
2791        if settings.hard_tabs {
2792            IndentSize::tab()
2793        } else {
2794            IndentSize::spaces(settings.tab_size.get())
2795        }
2796    }
2797
2798    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2799    /// is passed in as `single_indent_size`.
2800    pub fn suggested_indents(
2801        &self,
2802        rows: impl Iterator<Item = u32>,
2803        single_indent_size: IndentSize,
2804    ) -> BTreeMap<u32, IndentSize> {
2805        let mut result = BTreeMap::new();
2806
2807        for row_range in contiguous_ranges(rows, 10) {
2808            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2809                Some(suggestions) => suggestions,
2810                _ => break,
2811            };
2812
2813            for (row, suggestion) in row_range.zip(suggestions) {
2814                let indent_size = if let Some(suggestion) = suggestion {
2815                    result
2816                        .get(&suggestion.basis_row)
2817                        .copied()
2818                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2819                        .with_delta(suggestion.delta, single_indent_size)
2820                } else {
2821                    self.indent_size_for_line(row)
2822                };
2823
2824                result.insert(row, indent_size);
2825            }
2826        }
2827
2828        result
2829    }
2830
2831    fn suggest_autoindents(
2832        &self,
2833        row_range: Range<u32>,
2834    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2835        let config = &self.language.as_ref()?.config;
2836        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2837
2838        // Find the suggested indentation ranges based on the syntax tree.
2839        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2840        let end = Point::new(row_range.end, 0);
2841        let range = (start..end).to_offset(&self.text);
2842        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2843            Some(&grammar.indents_config.as_ref()?.query)
2844        });
2845        let indent_configs = matches
2846            .grammars()
2847            .iter()
2848            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2849            .collect::<Vec<_>>();
2850
2851        let mut indent_ranges = Vec::<Range<Point>>::new();
2852        let mut outdent_positions = Vec::<Point>::new();
2853        while let Some(mat) = matches.peek() {
2854            let mut start: Option<Point> = None;
2855            let mut end: Option<Point> = None;
2856
2857            let config = &indent_configs[mat.grammar_index];
2858            for capture in mat.captures {
2859                if capture.index == config.indent_capture_ix {
2860                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2861                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2862                } else if Some(capture.index) == config.start_capture_ix {
2863                    start = Some(Point::from_ts_point(capture.node.end_position()));
2864                } else if Some(capture.index) == config.end_capture_ix {
2865                    end = Some(Point::from_ts_point(capture.node.start_position()));
2866                } else if Some(capture.index) == config.outdent_capture_ix {
2867                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2868                }
2869            }
2870
2871            matches.advance();
2872            if let Some((start, end)) = start.zip(end) {
2873                if start.row == end.row {
2874                    continue;
2875                }
2876
2877                let range = start..end;
2878                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2879                    Err(ix) => indent_ranges.insert(ix, range),
2880                    Ok(ix) => {
2881                        let prev_range = &mut indent_ranges[ix];
2882                        prev_range.end = prev_range.end.max(range.end);
2883                    }
2884                }
2885            }
2886        }
2887
2888        let mut error_ranges = Vec::<Range<Point>>::new();
2889        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2890            grammar.error_query.as_ref()
2891        });
2892        while let Some(mat) = matches.peek() {
2893            let node = mat.captures[0].node;
2894            let start = Point::from_ts_point(node.start_position());
2895            let end = Point::from_ts_point(node.end_position());
2896            let range = start..end;
2897            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2898                Ok(ix) | Err(ix) => ix,
2899            };
2900            let mut end_ix = ix;
2901            while let Some(existing_range) = error_ranges.get(end_ix) {
2902                if existing_range.end < end {
2903                    end_ix += 1;
2904                } else {
2905                    break;
2906                }
2907            }
2908            error_ranges.splice(ix..end_ix, [range]);
2909            matches.advance();
2910        }
2911
2912        outdent_positions.sort();
2913        for outdent_position in outdent_positions {
2914            // find the innermost indent range containing this outdent_position
2915            // set its end to the outdent position
2916            if let Some(range_to_truncate) = indent_ranges
2917                .iter_mut()
2918                .filter(|indent_range| indent_range.contains(&outdent_position))
2919                .last()
2920            {
2921                range_to_truncate.end = outdent_position;
2922            }
2923        }
2924
2925        // Find the suggested indentation increases and decreased based on regexes.
2926        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2927        self.for_each_line(
2928            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2929                ..Point::new(row_range.end, 0),
2930            |row, line| {
2931                if config
2932                    .decrease_indent_pattern
2933                    .as_ref()
2934                    .map_or(false, |regex| regex.is_match(line))
2935                {
2936                    indent_change_rows.push((row, Ordering::Less));
2937                }
2938                if config
2939                    .increase_indent_pattern
2940                    .as_ref()
2941                    .map_or(false, |regex| regex.is_match(line))
2942                {
2943                    indent_change_rows.push((row + 1, Ordering::Greater));
2944                }
2945            },
2946        );
2947
2948        let mut indent_changes = indent_change_rows.into_iter().peekable();
2949        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2950            prev_non_blank_row.unwrap_or(0)
2951        } else {
2952            row_range.start.saturating_sub(1)
2953        };
2954        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2955        Some(row_range.map(move |row| {
2956            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2957
2958            let mut indent_from_prev_row = false;
2959            let mut outdent_from_prev_row = false;
2960            let mut outdent_to_row = u32::MAX;
2961            let mut from_regex = false;
2962
2963            while let Some((indent_row, delta)) = indent_changes.peek() {
2964                match indent_row.cmp(&row) {
2965                    Ordering::Equal => match delta {
2966                        Ordering::Less => {
2967                            from_regex = true;
2968                            outdent_from_prev_row = true
2969                        }
2970                        Ordering::Greater => {
2971                            indent_from_prev_row = true;
2972                            from_regex = true
2973                        }
2974                        _ => {}
2975                    },
2976
2977                    Ordering::Greater => break,
2978                    Ordering::Less => {}
2979                }
2980
2981                indent_changes.next();
2982            }
2983
2984            for range in &indent_ranges {
2985                if range.start.row >= row {
2986                    break;
2987                }
2988                if range.start.row == prev_row && range.end > row_start {
2989                    indent_from_prev_row = true;
2990                }
2991                if range.end > prev_row_start && range.end <= row_start {
2992                    outdent_to_row = outdent_to_row.min(range.start.row);
2993                }
2994            }
2995
2996            let within_error = error_ranges
2997                .iter()
2998                .any(|e| e.start.row < row && e.end > row_start);
2999
3000            let suggestion = if outdent_to_row == prev_row
3001                || (outdent_from_prev_row && indent_from_prev_row)
3002            {
3003                Some(IndentSuggestion {
3004                    basis_row: prev_row,
3005                    delta: Ordering::Equal,
3006                    within_error: within_error && !from_regex,
3007                })
3008            } else if indent_from_prev_row {
3009                Some(IndentSuggestion {
3010                    basis_row: prev_row,
3011                    delta: Ordering::Greater,
3012                    within_error: within_error && !from_regex,
3013                })
3014            } else if outdent_to_row < prev_row {
3015                Some(IndentSuggestion {
3016                    basis_row: outdent_to_row,
3017                    delta: Ordering::Equal,
3018                    within_error: within_error && !from_regex,
3019                })
3020            } else if outdent_from_prev_row {
3021                Some(IndentSuggestion {
3022                    basis_row: prev_row,
3023                    delta: Ordering::Less,
3024                    within_error: within_error && !from_regex,
3025                })
3026            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
3027            {
3028                Some(IndentSuggestion {
3029                    basis_row: prev_row,
3030                    delta: Ordering::Equal,
3031                    within_error: within_error && !from_regex,
3032                })
3033            } else {
3034                None
3035            };
3036
3037            prev_row = row;
3038            prev_row_start = row_start;
3039            suggestion
3040        }))
3041    }
3042
3043    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
3044        while row > 0 {
3045            row -= 1;
3046            if !self.is_line_blank(row) {
3047                return Some(row);
3048            }
3049        }
3050        None
3051    }
3052
3053    fn get_highlights(&self, range: Range<usize>) -> (SyntaxMapCaptures, Vec<HighlightMap>) {
3054        let captures = self.syntax.captures(range, &self.text, |grammar| {
3055            grammar.highlights_query.as_ref()
3056        });
3057        let highlight_maps = captures
3058            .grammars()
3059            .iter()
3060            .map(|grammar| grammar.highlight_map())
3061            .collect();
3062        (captures, highlight_maps)
3063    }
3064
3065    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
3066    /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
3067    /// returned in chunks where each chunk has a single syntax highlighting style and
3068    /// diagnostic status.
3069    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
3070        let range = range.start.to_offset(self)..range.end.to_offset(self);
3071
3072        let mut syntax = None;
3073        if language_aware {
3074            syntax = Some(self.get_highlights(range.clone()));
3075        }
3076        // We want to look at diagnostic spans only when iterating over language-annotated chunks.
3077        let diagnostics = language_aware;
3078        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostics, Some(self))
3079    }
3080
3081    pub fn highlighted_text_for_range<T: ToOffset>(
3082        &self,
3083        range: Range<T>,
3084        override_style: Option<HighlightStyle>,
3085        syntax_theme: &SyntaxTheme,
3086    ) -> HighlightedText {
3087        HighlightedText::from_buffer_range(
3088            range,
3089            &self.text,
3090            &self.syntax,
3091            override_style,
3092            syntax_theme,
3093        )
3094    }
3095
3096    /// Invokes the given callback for each line of text in the given range of the buffer.
3097    /// Uses callback to avoid allocating a string for each line.
3098    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
3099        let mut line = String::new();
3100        let mut row = range.start.row;
3101        for chunk in self
3102            .as_rope()
3103            .chunks_in_range(range.to_offset(self))
3104            .chain(["\n"])
3105        {
3106            for (newline_ix, text) in chunk.split('\n').enumerate() {
3107                if newline_ix > 0 {
3108                    callback(row, &line);
3109                    row += 1;
3110                    line.clear();
3111                }
3112                line.push_str(text);
3113            }
3114        }
3115    }
3116
3117    /// Iterates over every [`SyntaxLayer`] in the buffer.
3118    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
3119        self.syntax
3120            .layers_for_range(0..self.len(), &self.text, true)
3121    }
3122
3123    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
3124        let offset = position.to_offset(self);
3125        self.syntax
3126            .layers_for_range(offset..offset, &self.text, false)
3127            .filter(|l| l.node().end_byte() > offset)
3128            .last()
3129    }
3130
3131    pub fn smallest_syntax_layer_containing<D: ToOffset>(
3132        &self,
3133        range: Range<D>,
3134    ) -> Option<SyntaxLayer> {
3135        let range = range.to_offset(self);
3136        return self
3137            .syntax
3138            .layers_for_range(range, &self.text, false)
3139            .max_by(|a, b| {
3140                if a.depth != b.depth {
3141                    a.depth.cmp(&b.depth)
3142                } else if a.offset.0 != b.offset.0 {
3143                    a.offset.0.cmp(&b.offset.0)
3144                } else {
3145                    a.node().end_byte().cmp(&b.node().end_byte()).reverse()
3146                }
3147            });
3148    }
3149
3150    /// Returns the main [`Language`].
3151    pub fn language(&self) -> Option<&Arc<Language>> {
3152        self.language.as_ref()
3153    }
3154
3155    /// Returns the [`Language`] at the given location.
3156    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
3157        self.syntax_layer_at(position)
3158            .map(|info| info.language)
3159            .or(self.language.as_ref())
3160    }
3161
3162    /// Returns the settings for the language at the given location.
3163    pub fn settings_at<'a, D: ToOffset>(
3164        &'a self,
3165        position: D,
3166        cx: &'a App,
3167    ) -> Cow<'a, LanguageSettings> {
3168        language_settings(
3169            self.language_at(position).map(|l| l.name()),
3170            self.file.as_ref(),
3171            cx,
3172        )
3173    }
3174
3175    pub fn char_classifier_at<T: ToOffset>(&self, point: T) -> CharClassifier {
3176        CharClassifier::new(self.language_scope_at(point))
3177    }
3178
3179    /// Returns the [`LanguageScope`] at the given location.
3180    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
3181        let offset = position.to_offset(self);
3182        let mut scope = None;
3183        let mut smallest_range: Option<Range<usize>> = None;
3184
3185        // Use the layer that has the smallest node intersecting the given point.
3186        for layer in self
3187            .syntax
3188            .layers_for_range(offset..offset, &self.text, false)
3189        {
3190            let mut cursor = layer.node().walk();
3191
3192            let mut range = None;
3193            loop {
3194                let child_range = cursor.node().byte_range();
3195                if !child_range.to_inclusive().contains(&offset) {
3196                    break;
3197                }
3198
3199                range = Some(child_range);
3200                if cursor.goto_first_child_for_byte(offset).is_none() {
3201                    break;
3202                }
3203            }
3204
3205            if let Some(range) = range {
3206                if smallest_range
3207                    .as_ref()
3208                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
3209                {
3210                    smallest_range = Some(range);
3211                    scope = Some(LanguageScope {
3212                        language: layer.language.clone(),
3213                        override_id: layer.override_id(offset, &self.text),
3214                    });
3215                }
3216            }
3217        }
3218
3219        scope.or_else(|| {
3220            self.language.clone().map(|language| LanguageScope {
3221                language,
3222                override_id: None,
3223            })
3224        })
3225    }
3226
3227    /// Returns a tuple of the range and character kind of the word
3228    /// surrounding the given position.
3229    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
3230        let mut start = start.to_offset(self);
3231        let mut end = start;
3232        let mut next_chars = self.chars_at(start).peekable();
3233        let mut prev_chars = self.reversed_chars_at(start).peekable();
3234
3235        let classifier = self.char_classifier_at(start);
3236        let word_kind = cmp::max(
3237            prev_chars.peek().copied().map(|c| classifier.kind(c)),
3238            next_chars.peek().copied().map(|c| classifier.kind(c)),
3239        );
3240
3241        for ch in prev_chars {
3242            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3243                start -= ch.len_utf8();
3244            } else {
3245                break;
3246            }
3247        }
3248
3249        for ch in next_chars {
3250            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3251                end += ch.len_utf8();
3252            } else {
3253                break;
3254            }
3255        }
3256
3257        (start..end, word_kind)
3258    }
3259
3260    /// Returns the closest syntax node enclosing the given range.
3261    pub fn syntax_ancestor<'a, T: ToOffset>(
3262        &'a self,
3263        range: Range<T>,
3264    ) -> Option<tree_sitter::Node<'a>> {
3265        let range = range.start.to_offset(self)..range.end.to_offset(self);
3266        let mut result: Option<tree_sitter::Node<'a>> = None;
3267        'outer: for layer in self
3268            .syntax
3269            .layers_for_range(range.clone(), &self.text, true)
3270        {
3271            let mut cursor = layer.node().walk();
3272
3273            // Descend to the first leaf that touches the start of the range,
3274            // and if the range is non-empty, extends beyond the start.
3275            while cursor.goto_first_child_for_byte(range.start).is_some() {
3276                if !range.is_empty() && cursor.node().end_byte() == range.start {
3277                    cursor.goto_next_sibling();
3278                }
3279            }
3280
3281            // Ascend to the smallest ancestor that strictly contains the range.
3282            loop {
3283                let node_range = cursor.node().byte_range();
3284                if node_range.start <= range.start
3285                    && node_range.end >= range.end
3286                    && node_range.len() > range.len()
3287                {
3288                    break;
3289                }
3290                if !cursor.goto_parent() {
3291                    continue 'outer;
3292                }
3293            }
3294
3295            let left_node = cursor.node();
3296            let mut layer_result = left_node;
3297
3298            // For an empty range, try to find another node immediately to the right of the range.
3299            if left_node.end_byte() == range.start {
3300                let mut right_node = None;
3301                while !cursor.goto_next_sibling() {
3302                    if !cursor.goto_parent() {
3303                        break;
3304                    }
3305                }
3306
3307                while cursor.node().start_byte() == range.start {
3308                    right_node = Some(cursor.node());
3309                    if !cursor.goto_first_child() {
3310                        break;
3311                    }
3312                }
3313
3314                // If there is a candidate node on both sides of the (empty) range, then
3315                // decide between the two by favoring a named node over an anonymous token.
3316                // If both nodes are the same in that regard, favor the right one.
3317                if let Some(right_node) = right_node {
3318                    if right_node.is_named() || !left_node.is_named() {
3319                        layer_result = right_node;
3320                    }
3321                }
3322            }
3323
3324            if let Some(previous_result) = &result {
3325                if previous_result.byte_range().len() < layer_result.byte_range().len() {
3326                    continue;
3327                }
3328            }
3329            result = Some(layer_result);
3330        }
3331
3332        result
3333    }
3334
3335    /// Returns the outline for the buffer.
3336    ///
3337    /// This method allows passing an optional [`SyntaxTheme`] to
3338    /// syntax-highlight the returned symbols.
3339    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3340        self.outline_items_containing(0..self.len(), true, theme)
3341            .map(Outline::new)
3342    }
3343
3344    /// Returns all the symbols that contain the given position.
3345    ///
3346    /// This method allows passing an optional [`SyntaxTheme`] to
3347    /// syntax-highlight the returned symbols.
3348    pub fn symbols_containing<T: ToOffset>(
3349        &self,
3350        position: T,
3351        theme: Option<&SyntaxTheme>,
3352    ) -> Option<Vec<OutlineItem<Anchor>>> {
3353        let position = position.to_offset(self);
3354        let mut items = self.outline_items_containing(
3355            position.saturating_sub(1)..self.len().min(position + 1),
3356            false,
3357            theme,
3358        )?;
3359        let mut prev_depth = None;
3360        items.retain(|item| {
3361            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
3362            prev_depth = Some(item.depth);
3363            result
3364        });
3365        Some(items)
3366    }
3367
3368    pub fn outline_range_containing<T: ToOffset>(&self, range: Range<T>) -> Option<Range<Point>> {
3369        let range = range.to_offset(self);
3370        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3371            grammar.outline_config.as_ref().map(|c| &c.query)
3372        });
3373        let configs = matches
3374            .grammars()
3375            .iter()
3376            .map(|g| g.outline_config.as_ref().unwrap())
3377            .collect::<Vec<_>>();
3378
3379        while let Some(mat) = matches.peek() {
3380            let config = &configs[mat.grammar_index];
3381            let containing_item_node = maybe!({
3382                let item_node = mat.captures.iter().find_map(|cap| {
3383                    if cap.index == config.item_capture_ix {
3384                        Some(cap.node)
3385                    } else {
3386                        None
3387                    }
3388                })?;
3389
3390                let item_byte_range = item_node.byte_range();
3391                if item_byte_range.end < range.start || item_byte_range.start > range.end {
3392                    None
3393                } else {
3394                    Some(item_node)
3395                }
3396            });
3397
3398            if let Some(item_node) = containing_item_node {
3399                return Some(
3400                    Point::from_ts_point(item_node.start_position())
3401                        ..Point::from_ts_point(item_node.end_position()),
3402                );
3403            }
3404
3405            matches.advance();
3406        }
3407        None
3408    }
3409
3410    pub fn outline_items_containing<T: ToOffset>(
3411        &self,
3412        range: Range<T>,
3413        include_extra_context: bool,
3414        theme: Option<&SyntaxTheme>,
3415    ) -> Option<Vec<OutlineItem<Anchor>>> {
3416        let range = range.to_offset(self);
3417        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3418            grammar.outline_config.as_ref().map(|c| &c.query)
3419        });
3420        let configs = matches
3421            .grammars()
3422            .iter()
3423            .map(|g| g.outline_config.as_ref().unwrap())
3424            .collect::<Vec<_>>();
3425
3426        let mut items = Vec::new();
3427        let mut annotation_row_ranges: Vec<Range<u32>> = Vec::new();
3428        while let Some(mat) = matches.peek() {
3429            let config = &configs[mat.grammar_index];
3430            if let Some(item) =
3431                self.next_outline_item(config, &mat, &range, include_extra_context, theme)
3432            {
3433                items.push(item);
3434            } else if let Some(capture) = mat
3435                .captures
3436                .iter()
3437                .find(|capture| Some(capture.index) == config.annotation_capture_ix)
3438            {
3439                let capture_range = capture.node.start_position()..capture.node.end_position();
3440                let mut capture_row_range =
3441                    capture_range.start.row as u32..capture_range.end.row as u32;
3442                if capture_range.end.row > capture_range.start.row && capture_range.end.column == 0
3443                {
3444                    capture_row_range.end -= 1;
3445                }
3446                if let Some(last_row_range) = annotation_row_ranges.last_mut() {
3447                    if last_row_range.end >= capture_row_range.start.saturating_sub(1) {
3448                        last_row_range.end = capture_row_range.end;
3449                    } else {
3450                        annotation_row_ranges.push(capture_row_range);
3451                    }
3452                } else {
3453                    annotation_row_ranges.push(capture_row_range);
3454                }
3455            }
3456            matches.advance();
3457        }
3458
3459        items.sort_by_key(|item| (item.range.start, Reverse(item.range.end)));
3460
3461        // Assign depths based on containment relationships and convert to anchors.
3462        let mut item_ends_stack = Vec::<Point>::new();
3463        let mut anchor_items = Vec::new();
3464        let mut annotation_row_ranges = annotation_row_ranges.into_iter().peekable();
3465        for item in items {
3466            while let Some(last_end) = item_ends_stack.last().copied() {
3467                if last_end < item.range.end {
3468                    item_ends_stack.pop();
3469                } else {
3470                    break;
3471                }
3472            }
3473
3474            let mut annotation_row_range = None;
3475            while let Some(next_annotation_row_range) = annotation_row_ranges.peek() {
3476                let row_preceding_item = item.range.start.row.saturating_sub(1);
3477                if next_annotation_row_range.end < row_preceding_item {
3478                    annotation_row_ranges.next();
3479                } else {
3480                    if next_annotation_row_range.end == row_preceding_item {
3481                        annotation_row_range = Some(next_annotation_row_range.clone());
3482                        annotation_row_ranges.next();
3483                    }
3484                    break;
3485                }
3486            }
3487
3488            anchor_items.push(OutlineItem {
3489                depth: item_ends_stack.len(),
3490                range: self.anchor_after(item.range.start)..self.anchor_before(item.range.end),
3491                text: item.text,
3492                highlight_ranges: item.highlight_ranges,
3493                name_ranges: item.name_ranges,
3494                body_range: item.body_range.map(|body_range| {
3495                    self.anchor_after(body_range.start)..self.anchor_before(body_range.end)
3496                }),
3497                annotation_range: annotation_row_range.map(|annotation_range| {
3498                    self.anchor_after(Point::new(annotation_range.start, 0))
3499                        ..self.anchor_before(Point::new(
3500                            annotation_range.end,
3501                            self.line_len(annotation_range.end),
3502                        ))
3503                }),
3504            });
3505            item_ends_stack.push(item.range.end);
3506        }
3507
3508        Some(anchor_items)
3509    }
3510
3511    fn next_outline_item(
3512        &self,
3513        config: &OutlineConfig,
3514        mat: &SyntaxMapMatch,
3515        range: &Range<usize>,
3516        include_extra_context: bool,
3517        theme: Option<&SyntaxTheme>,
3518    ) -> Option<OutlineItem<Point>> {
3519        let item_node = mat.captures.iter().find_map(|cap| {
3520            if cap.index == config.item_capture_ix {
3521                Some(cap.node)
3522            } else {
3523                None
3524            }
3525        })?;
3526
3527        let item_byte_range = item_node.byte_range();
3528        if item_byte_range.end < range.start || item_byte_range.start > range.end {
3529            return None;
3530        }
3531        let item_point_range = Point::from_ts_point(item_node.start_position())
3532            ..Point::from_ts_point(item_node.end_position());
3533
3534        let mut open_point = None;
3535        let mut close_point = None;
3536        let mut buffer_ranges = Vec::new();
3537        for capture in mat.captures {
3538            let node_is_name;
3539            if capture.index == config.name_capture_ix {
3540                node_is_name = true;
3541            } else if Some(capture.index) == config.context_capture_ix
3542                || (Some(capture.index) == config.extra_context_capture_ix && include_extra_context)
3543            {
3544                node_is_name = false;
3545            } else {
3546                if Some(capture.index) == config.open_capture_ix {
3547                    open_point = Some(Point::from_ts_point(capture.node.end_position()));
3548                } else if Some(capture.index) == config.close_capture_ix {
3549                    close_point = Some(Point::from_ts_point(capture.node.start_position()));
3550                }
3551
3552                continue;
3553            }
3554
3555            let mut range = capture.node.start_byte()..capture.node.end_byte();
3556            let start = capture.node.start_position();
3557            if capture.node.end_position().row > start.row {
3558                range.end = range.start + self.line_len(start.row as u32) as usize - start.column;
3559            }
3560
3561            if !range.is_empty() {
3562                buffer_ranges.push((range, node_is_name));
3563            }
3564        }
3565        if buffer_ranges.is_empty() {
3566            return None;
3567        }
3568        let mut text = String::new();
3569        let mut highlight_ranges = Vec::new();
3570        let mut name_ranges = Vec::new();
3571        let mut chunks = self.chunks(
3572            buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
3573            true,
3574        );
3575        let mut last_buffer_range_end = 0;
3576
3577        for (buffer_range, is_name) in buffer_ranges {
3578            let space_added = !text.is_empty() && buffer_range.start > last_buffer_range_end;
3579            if space_added {
3580                text.push(' ');
3581            }
3582            let before_append_len = text.len();
3583            let mut offset = buffer_range.start;
3584            chunks.seek(buffer_range.clone());
3585            for mut chunk in chunks.by_ref() {
3586                if chunk.text.len() > buffer_range.end - offset {
3587                    chunk.text = &chunk.text[0..(buffer_range.end - offset)];
3588                    offset = buffer_range.end;
3589                } else {
3590                    offset += chunk.text.len();
3591                }
3592                let style = chunk
3593                    .syntax_highlight_id
3594                    .zip(theme)
3595                    .and_then(|(highlight, theme)| highlight.style(theme));
3596                if let Some(style) = style {
3597                    let start = text.len();
3598                    let end = start + chunk.text.len();
3599                    highlight_ranges.push((start..end, style));
3600                }
3601                text.push_str(chunk.text);
3602                if offset >= buffer_range.end {
3603                    break;
3604                }
3605            }
3606            if is_name {
3607                let after_append_len = text.len();
3608                let start = if space_added && !name_ranges.is_empty() {
3609                    before_append_len - 1
3610                } else {
3611                    before_append_len
3612                };
3613                name_ranges.push(start..after_append_len);
3614            }
3615            last_buffer_range_end = buffer_range.end;
3616        }
3617
3618        Some(OutlineItem {
3619            depth: 0, // We'll calculate the depth later
3620            range: item_point_range,
3621            text,
3622            highlight_ranges,
3623            name_ranges,
3624            body_range: open_point.zip(close_point).map(|(start, end)| start..end),
3625            annotation_range: None,
3626        })
3627    }
3628
3629    pub fn function_body_fold_ranges<T: ToOffset>(
3630        &self,
3631        within: Range<T>,
3632    ) -> impl Iterator<Item = Range<usize>> + '_ {
3633        self.text_object_ranges(within, TreeSitterOptions::default())
3634            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
3635    }
3636
3637    /// For each grammar in the language, runs the provided
3638    /// [`tree_sitter::Query`] against the given range.
3639    pub fn matches(
3640        &self,
3641        range: Range<usize>,
3642        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
3643    ) -> SyntaxMapMatches {
3644        self.syntax.matches(range, self, query)
3645    }
3646
3647    pub fn all_bracket_ranges(
3648        &self,
3649        range: Range<usize>,
3650    ) -> impl Iterator<Item = BracketMatch> + '_ {
3651        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3652            grammar.brackets_config.as_ref().map(|c| &c.query)
3653        });
3654        let configs = matches
3655            .grammars()
3656            .iter()
3657            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
3658            .collect::<Vec<_>>();
3659
3660        iter::from_fn(move || {
3661            while let Some(mat) = matches.peek() {
3662                let mut open = None;
3663                let mut close = None;
3664                let config = &configs[mat.grammar_index];
3665                let pattern = &config.patterns[mat.pattern_index];
3666                for capture in mat.captures {
3667                    if capture.index == config.open_capture_ix {
3668                        open = Some(capture.node.byte_range());
3669                    } else if capture.index == config.close_capture_ix {
3670                        close = Some(capture.node.byte_range());
3671                    }
3672                }
3673
3674                matches.advance();
3675
3676                let Some((open_range, close_range)) = open.zip(close) else {
3677                    continue;
3678                };
3679
3680                let bracket_range = open_range.start..=close_range.end;
3681                if !bracket_range.overlaps(&range) {
3682                    continue;
3683                }
3684
3685                return Some(BracketMatch {
3686                    open_range,
3687                    close_range,
3688                    newline_only: pattern.newline_only,
3689                });
3690            }
3691            None
3692        })
3693    }
3694
3695    /// Returns bracket range pairs overlapping or adjacent to `range`
3696    pub fn bracket_ranges<T: ToOffset>(
3697        &self,
3698        range: Range<T>,
3699    ) -> impl Iterator<Item = BracketMatch> + '_ {
3700        // Find bracket pairs that *inclusively* contain the given range.
3701        let range = range.start.to_offset(self).saturating_sub(1)
3702            ..self.len().min(range.end.to_offset(self) + 1);
3703        self.all_bracket_ranges(range)
3704            .filter(|pair| !pair.newline_only)
3705    }
3706
3707    pub fn text_object_ranges<T: ToOffset>(
3708        &self,
3709        range: Range<T>,
3710        options: TreeSitterOptions,
3711    ) -> impl Iterator<Item = (Range<usize>, TextObject)> + '_ {
3712        let range = range.start.to_offset(self).saturating_sub(1)
3713            ..self.len().min(range.end.to_offset(self) + 1);
3714
3715        let mut matches =
3716            self.syntax
3717                .matches_with_options(range.clone(), &self.text, options, |grammar| {
3718                    grammar.text_object_config.as_ref().map(|c| &c.query)
3719                });
3720
3721        let configs = matches
3722            .grammars()
3723            .iter()
3724            .map(|grammar| grammar.text_object_config.as_ref())
3725            .collect::<Vec<_>>();
3726
3727        let mut captures = Vec::<(Range<usize>, TextObject)>::new();
3728
3729        iter::from_fn(move || {
3730            loop {
3731                while let Some(capture) = captures.pop() {
3732                    if capture.0.overlaps(&range) {
3733                        return Some(capture);
3734                    }
3735                }
3736
3737                let mat = matches.peek()?;
3738
3739                let Some(config) = configs[mat.grammar_index].as_ref() else {
3740                    matches.advance();
3741                    continue;
3742                };
3743
3744                for capture in mat.captures {
3745                    let Some(ix) = config
3746                        .text_objects_by_capture_ix
3747                        .binary_search_by_key(&capture.index, |e| e.0)
3748                        .ok()
3749                    else {
3750                        continue;
3751                    };
3752                    let text_object = config.text_objects_by_capture_ix[ix].1;
3753                    let byte_range = capture.node.byte_range();
3754
3755                    let mut found = false;
3756                    for (range, existing) in captures.iter_mut() {
3757                        if existing == &text_object {
3758                            range.start = range.start.min(byte_range.start);
3759                            range.end = range.end.max(byte_range.end);
3760                            found = true;
3761                            break;
3762                        }
3763                    }
3764
3765                    if !found {
3766                        captures.push((byte_range, text_object));
3767                    }
3768                }
3769
3770                matches.advance();
3771            }
3772        })
3773    }
3774
3775    /// Returns enclosing bracket ranges containing the given range
3776    pub fn enclosing_bracket_ranges<T: ToOffset>(
3777        &self,
3778        range: Range<T>,
3779    ) -> impl Iterator<Item = BracketMatch> + '_ {
3780        let range = range.start.to_offset(self)..range.end.to_offset(self);
3781
3782        self.bracket_ranges(range.clone()).filter(move |pair| {
3783            pair.open_range.start <= range.start && pair.close_range.end >= range.end
3784        })
3785    }
3786
3787    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3788    ///
3789    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3790    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3791        &self,
3792        range: Range<T>,
3793        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3794    ) -> Option<(Range<usize>, Range<usize>)> {
3795        let range = range.start.to_offset(self)..range.end.to_offset(self);
3796
3797        // Get the ranges of the innermost pair of brackets.
3798        let mut result: Option<(Range<usize>, Range<usize>)> = None;
3799
3800        for pair in self.enclosing_bracket_ranges(range.clone()) {
3801            if let Some(range_filter) = range_filter {
3802                if !range_filter(pair.open_range.clone(), pair.close_range.clone()) {
3803                    continue;
3804                }
3805            }
3806
3807            let len = pair.close_range.end - pair.open_range.start;
3808
3809            if let Some((existing_open, existing_close)) = &result {
3810                let existing_len = existing_close.end - existing_open.start;
3811                if len > existing_len {
3812                    continue;
3813                }
3814            }
3815
3816            result = Some((pair.open_range, pair.close_range));
3817        }
3818
3819        result
3820    }
3821
3822    /// Returns anchor ranges for any matches of the redaction query.
3823    /// The buffer can be associated with multiple languages, and the redaction query associated with each
3824    /// will be run on the relevant section of the buffer.
3825    pub fn redacted_ranges<T: ToOffset>(
3826        &self,
3827        range: Range<T>,
3828    ) -> impl Iterator<Item = Range<usize>> + '_ {
3829        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3830        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3831            grammar
3832                .redactions_config
3833                .as_ref()
3834                .map(|config| &config.query)
3835        });
3836
3837        let configs = syntax_matches
3838            .grammars()
3839            .iter()
3840            .map(|grammar| grammar.redactions_config.as_ref())
3841            .collect::<Vec<_>>();
3842
3843        iter::from_fn(move || {
3844            let redacted_range = syntax_matches
3845                .peek()
3846                .and_then(|mat| {
3847                    configs[mat.grammar_index].and_then(|config| {
3848                        mat.captures
3849                            .iter()
3850                            .find(|capture| capture.index == config.redaction_capture_ix)
3851                    })
3852                })
3853                .map(|mat| mat.node.byte_range());
3854            syntax_matches.advance();
3855            redacted_range
3856        })
3857    }
3858
3859    pub fn injections_intersecting_range<T: ToOffset>(
3860        &self,
3861        range: Range<T>,
3862    ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3863        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3864
3865        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3866            grammar
3867                .injection_config
3868                .as_ref()
3869                .map(|config| &config.query)
3870        });
3871
3872        let configs = syntax_matches
3873            .grammars()
3874            .iter()
3875            .map(|grammar| grammar.injection_config.as_ref())
3876            .collect::<Vec<_>>();
3877
3878        iter::from_fn(move || {
3879            let ranges = syntax_matches.peek().and_then(|mat| {
3880                let config = &configs[mat.grammar_index]?;
3881                let content_capture_range = mat.captures.iter().find_map(|capture| {
3882                    if capture.index == config.content_capture_ix {
3883                        Some(capture.node.byte_range())
3884                    } else {
3885                        None
3886                    }
3887                })?;
3888                let language = self.language_at(content_capture_range.start)?;
3889                Some((content_capture_range, language))
3890            });
3891            syntax_matches.advance();
3892            ranges
3893        })
3894    }
3895
3896    pub fn runnable_ranges(
3897        &self,
3898        offset_range: Range<usize>,
3899    ) -> impl Iterator<Item = RunnableRange> + '_ {
3900        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3901            grammar.runnable_config.as_ref().map(|config| &config.query)
3902        });
3903
3904        let test_configs = syntax_matches
3905            .grammars()
3906            .iter()
3907            .map(|grammar| grammar.runnable_config.as_ref())
3908            .collect::<Vec<_>>();
3909
3910        iter::from_fn(move || {
3911            loop {
3912                let mat = syntax_matches.peek()?;
3913
3914                let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3915                    let mut run_range = None;
3916                    let full_range = mat.captures.iter().fold(
3917                        Range {
3918                            start: usize::MAX,
3919                            end: 0,
3920                        },
3921                        |mut acc, next| {
3922                            let byte_range = next.node.byte_range();
3923                            if acc.start > byte_range.start {
3924                                acc.start = byte_range.start;
3925                            }
3926                            if acc.end < byte_range.end {
3927                                acc.end = byte_range.end;
3928                            }
3929                            acc
3930                        },
3931                    );
3932                    if full_range.start > full_range.end {
3933                        // We did not find a full spanning range of this match.
3934                        return None;
3935                    }
3936                    let extra_captures: SmallVec<[_; 1]> =
3937                        SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3938                            test_configs
3939                                .extra_captures
3940                                .get(capture.index as usize)
3941                                .cloned()
3942                                .and_then(|tag_name| match tag_name {
3943                                    RunnableCapture::Named(name) => {
3944                                        Some((capture.node.byte_range(), name))
3945                                    }
3946                                    RunnableCapture::Run => {
3947                                        let _ = run_range.insert(capture.node.byte_range());
3948                                        None
3949                                    }
3950                                })
3951                        }));
3952                    let run_range = run_range?;
3953                    let tags = test_configs
3954                        .query
3955                        .property_settings(mat.pattern_index)
3956                        .iter()
3957                        .filter_map(|property| {
3958                            if *property.key == *"tag" {
3959                                property
3960                                    .value
3961                                    .as_ref()
3962                                    .map(|value| RunnableTag(value.to_string().into()))
3963                            } else {
3964                                None
3965                            }
3966                        })
3967                        .collect();
3968                    let extra_captures = extra_captures
3969                        .into_iter()
3970                        .map(|(range, name)| {
3971                            (
3972                                name.to_string(),
3973                                self.text_for_range(range.clone()).collect::<String>(),
3974                            )
3975                        })
3976                        .collect();
3977                    // All tags should have the same range.
3978                    Some(RunnableRange {
3979                        run_range,
3980                        full_range,
3981                        runnable: Runnable {
3982                            tags,
3983                            language: mat.language,
3984                            buffer: self.remote_id(),
3985                        },
3986                        extra_captures,
3987                        buffer_id: self.remote_id(),
3988                    })
3989                });
3990
3991                syntax_matches.advance();
3992                if test_range.is_some() {
3993                    // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
3994                    // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
3995                    return test_range;
3996                }
3997            }
3998        })
3999    }
4000
4001    /// Returns selections for remote peers intersecting the given range.
4002    #[allow(clippy::type_complexity)]
4003    pub fn selections_in_range(
4004        &self,
4005        range: Range<Anchor>,
4006        include_local: bool,
4007    ) -> impl Iterator<
4008        Item = (
4009            ReplicaId,
4010            bool,
4011            CursorShape,
4012            impl Iterator<Item = &Selection<Anchor>> + '_,
4013        ),
4014    > + '_ {
4015        self.remote_selections
4016            .iter()
4017            .filter(move |(replica_id, set)| {
4018                (include_local || **replica_id != self.text.replica_id())
4019                    && !set.selections.is_empty()
4020            })
4021            .map(move |(replica_id, set)| {
4022                let start_ix = match set.selections.binary_search_by(|probe| {
4023                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
4024                }) {
4025                    Ok(ix) | Err(ix) => ix,
4026                };
4027                let end_ix = match set.selections.binary_search_by(|probe| {
4028                    probe.start.cmp(&range.end, self).then(Ordering::Less)
4029                }) {
4030                    Ok(ix) | Err(ix) => ix,
4031                };
4032
4033                (
4034                    *replica_id,
4035                    set.line_mode,
4036                    set.cursor_shape,
4037                    set.selections[start_ix..end_ix].iter(),
4038                )
4039            })
4040    }
4041
4042    /// Returns if the buffer contains any diagnostics.
4043    pub fn has_diagnostics(&self) -> bool {
4044        !self.diagnostics.is_empty()
4045    }
4046
4047    /// Returns all the diagnostics intersecting the given range.
4048    pub fn diagnostics_in_range<'a, T, O>(
4049        &'a self,
4050        search_range: Range<T>,
4051        reversed: bool,
4052    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
4053    where
4054        T: 'a + Clone + ToOffset,
4055        O: 'a + FromAnchor,
4056    {
4057        let mut iterators: Vec<_> = self
4058            .diagnostics
4059            .iter()
4060            .map(|(_, collection)| {
4061                collection
4062                    .range::<T, text::Anchor>(search_range.clone(), self, true, reversed)
4063                    .peekable()
4064            })
4065            .collect();
4066
4067        std::iter::from_fn(move || {
4068            let (next_ix, _) = iterators
4069                .iter_mut()
4070                .enumerate()
4071                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
4072                .min_by(|(_, a), (_, b)| {
4073                    let cmp = a
4074                        .range
4075                        .start
4076                        .cmp(&b.range.start, self)
4077                        // when range is equal, sort by diagnostic severity
4078                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
4079                        // and stabilize order with group_id
4080                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
4081                    if reversed { cmp.reverse() } else { cmp }
4082                })?;
4083            iterators[next_ix]
4084                .next()
4085                .map(|DiagnosticEntry { range, diagnostic }| DiagnosticEntry {
4086                    diagnostic,
4087                    range: FromAnchor::from_anchor(&range.start, self)
4088                        ..FromAnchor::from_anchor(&range.end, self),
4089                })
4090        })
4091    }
4092
4093    /// Returns all the diagnostic groups associated with the given
4094    /// language server ID. If no language server ID is provided,
4095    /// all diagnostics groups are returned.
4096    pub fn diagnostic_groups(
4097        &self,
4098        language_server_id: Option<LanguageServerId>,
4099    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
4100        let mut groups = Vec::new();
4101
4102        if let Some(language_server_id) = language_server_id {
4103            if let Ok(ix) = self
4104                .diagnostics
4105                .binary_search_by_key(&language_server_id, |e| e.0)
4106            {
4107                self.diagnostics[ix]
4108                    .1
4109                    .groups(language_server_id, &mut groups, self);
4110            }
4111        } else {
4112            for (language_server_id, diagnostics) in self.diagnostics.iter() {
4113                diagnostics.groups(*language_server_id, &mut groups, self);
4114            }
4115        }
4116
4117        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
4118            let a_start = &group_a.entries[group_a.primary_ix].range.start;
4119            let b_start = &group_b.entries[group_b.primary_ix].range.start;
4120            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
4121        });
4122
4123        groups
4124    }
4125
4126    /// Returns an iterator over the diagnostics for the given group.
4127    pub fn diagnostic_group<O>(
4128        &self,
4129        group_id: usize,
4130    ) -> impl Iterator<Item = DiagnosticEntry<O>> + '_
4131    where
4132        O: FromAnchor + 'static,
4133    {
4134        self.diagnostics
4135            .iter()
4136            .flat_map(move |(_, set)| set.group(group_id, self))
4137    }
4138
4139    /// An integer version number that accounts for all updates besides
4140    /// the buffer's text itself (which is versioned via a version vector).
4141    pub fn non_text_state_update_count(&self) -> usize {
4142        self.non_text_state_update_count
4143    }
4144
4145    /// Returns a snapshot of underlying file.
4146    pub fn file(&self) -> Option<&Arc<dyn File>> {
4147        self.file.as_ref()
4148    }
4149
4150    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
4151    pub fn resolve_file_path(&self, cx: &App, include_root: bool) -> Option<PathBuf> {
4152        if let Some(file) = self.file() {
4153            if file.path().file_name().is_none() || include_root {
4154                Some(file.full_path(cx))
4155            } else {
4156                Some(file.path().to_path_buf())
4157            }
4158        } else {
4159            None
4160        }
4161    }
4162
4163    pub fn words_in_range(&self, query: WordsQuery) -> HashMap<String, Range<Anchor>> {
4164        let query_str = query.fuzzy_contents;
4165        if query_str.map_or(false, |query| query.is_empty()) {
4166            return HashMap::default();
4167        }
4168
4169        let classifier = CharClassifier::new(self.language.clone().map(|language| LanguageScope {
4170            language,
4171            override_id: None,
4172        }));
4173
4174        let mut query_ix = 0;
4175        let query_chars = query_str.map(|query| query.chars().collect::<Vec<_>>());
4176        let query_len = query_chars.as_ref().map_or(0, |query| query.len());
4177
4178        let mut words = HashMap::default();
4179        let mut current_word_start_ix = None;
4180        let mut chunk_ix = query.range.start;
4181        for chunk in self.chunks(query.range, false) {
4182            for (i, c) in chunk.text.char_indices() {
4183                let ix = chunk_ix + i;
4184                if classifier.is_word(c) {
4185                    if current_word_start_ix.is_none() {
4186                        current_word_start_ix = Some(ix);
4187                    }
4188
4189                    if let Some(query_chars) = &query_chars {
4190                        if query_ix < query_len {
4191                            if c.to_lowercase().eq(query_chars[query_ix].to_lowercase()) {
4192                                query_ix += 1;
4193                            }
4194                        }
4195                    }
4196                    continue;
4197                } else if let Some(word_start) = current_word_start_ix.take() {
4198                    if query_ix == query_len {
4199                        let word_range = self.anchor_before(word_start)..self.anchor_after(ix);
4200                        let mut word_text = self.text_for_range(word_start..ix).peekable();
4201                        let first_char = word_text
4202                            .peek()
4203                            .and_then(|first_chunk| first_chunk.chars().next());
4204                        // Skip empty and "words" starting with digits as a heuristic to reduce useless completions
4205                        if !query.skip_digits
4206                            || first_char.map_or(true, |first_char| !first_char.is_digit(10))
4207                        {
4208                            words.insert(word_text.collect(), word_range);
4209                        }
4210                    }
4211                }
4212                query_ix = 0;
4213            }
4214            chunk_ix += chunk.text.len();
4215        }
4216
4217        words
4218    }
4219}
4220
4221pub struct WordsQuery<'a> {
4222    /// Only returns words with all chars from the fuzzy string in them.
4223    pub fuzzy_contents: Option<&'a str>,
4224    /// Skips words that start with a digit.
4225    pub skip_digits: bool,
4226    /// Buffer offset range, to look for words.
4227    pub range: Range<usize>,
4228}
4229
4230fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
4231    indent_size_for_text(text.chars_at(Point::new(row, 0)))
4232}
4233
4234fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
4235    let mut result = IndentSize::spaces(0);
4236    for c in text {
4237        let kind = match c {
4238            ' ' => IndentKind::Space,
4239            '\t' => IndentKind::Tab,
4240            _ => break,
4241        };
4242        if result.len == 0 {
4243            result.kind = kind;
4244        }
4245        result.len += 1;
4246    }
4247    result
4248}
4249
4250impl Clone for BufferSnapshot {
4251    fn clone(&self) -> Self {
4252        Self {
4253            text: self.text.clone(),
4254            syntax: self.syntax.clone(),
4255            file: self.file.clone(),
4256            remote_selections: self.remote_selections.clone(),
4257            diagnostics: self.diagnostics.clone(),
4258            language: self.language.clone(),
4259            non_text_state_update_count: self.non_text_state_update_count,
4260        }
4261    }
4262}
4263
4264impl Deref for BufferSnapshot {
4265    type Target = text::BufferSnapshot;
4266
4267    fn deref(&self) -> &Self::Target {
4268        &self.text
4269    }
4270}
4271
4272unsafe impl Send for BufferChunks<'_> {}
4273
4274impl<'a> BufferChunks<'a> {
4275    pub(crate) fn new(
4276        text: &'a Rope,
4277        range: Range<usize>,
4278        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
4279        diagnostics: bool,
4280        buffer_snapshot: Option<&'a BufferSnapshot>,
4281    ) -> Self {
4282        let mut highlights = None;
4283        if let Some((captures, highlight_maps)) = syntax {
4284            highlights = Some(BufferChunkHighlights {
4285                captures,
4286                next_capture: None,
4287                stack: Default::default(),
4288                highlight_maps,
4289            })
4290        }
4291
4292        let diagnostic_endpoints = diagnostics.then(|| Vec::new().into_iter().peekable());
4293        let chunks = text.chunks_in_range(range.clone());
4294
4295        let mut this = BufferChunks {
4296            range,
4297            buffer_snapshot,
4298            chunks,
4299            diagnostic_endpoints,
4300            error_depth: 0,
4301            warning_depth: 0,
4302            information_depth: 0,
4303            hint_depth: 0,
4304            unnecessary_depth: 0,
4305            highlights,
4306        };
4307        this.initialize_diagnostic_endpoints();
4308        this
4309    }
4310
4311    /// Seeks to the given byte offset in the buffer.
4312    pub fn seek(&mut self, range: Range<usize>) {
4313        let old_range = std::mem::replace(&mut self.range, range.clone());
4314        self.chunks.set_range(self.range.clone());
4315        if let Some(highlights) = self.highlights.as_mut() {
4316            if old_range.start <= self.range.start && old_range.end >= self.range.end {
4317                // Reuse existing highlights stack, as the new range is a subrange of the old one.
4318                highlights
4319                    .stack
4320                    .retain(|(end_offset, _)| *end_offset > range.start);
4321                if let Some(capture) = &highlights.next_capture {
4322                    if range.start >= capture.node.start_byte() {
4323                        let next_capture_end = capture.node.end_byte();
4324                        if range.start < next_capture_end {
4325                            highlights.stack.push((
4326                                next_capture_end,
4327                                highlights.highlight_maps[capture.grammar_index].get(capture.index),
4328                            ));
4329                        }
4330                        highlights.next_capture.take();
4331                    }
4332                }
4333            } else if let Some(snapshot) = self.buffer_snapshot {
4334                let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
4335                *highlights = BufferChunkHighlights {
4336                    captures,
4337                    next_capture: None,
4338                    stack: Default::default(),
4339                    highlight_maps,
4340                };
4341            } else {
4342                // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
4343                // Seeking such BufferChunks is not supported.
4344                debug_assert!(
4345                    false,
4346                    "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot"
4347                );
4348            }
4349
4350            highlights.captures.set_byte_range(self.range.clone());
4351            self.initialize_diagnostic_endpoints();
4352        }
4353    }
4354
4355    fn initialize_diagnostic_endpoints(&mut self) {
4356        if let Some(diagnostics) = self.diagnostic_endpoints.as_mut() {
4357            if let Some(buffer) = self.buffer_snapshot {
4358                let mut diagnostic_endpoints = Vec::new();
4359                for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
4360                    diagnostic_endpoints.push(DiagnosticEndpoint {
4361                        offset: entry.range.start,
4362                        is_start: true,
4363                        severity: entry.diagnostic.severity,
4364                        is_unnecessary: entry.diagnostic.is_unnecessary,
4365                    });
4366                    diagnostic_endpoints.push(DiagnosticEndpoint {
4367                        offset: entry.range.end,
4368                        is_start: false,
4369                        severity: entry.diagnostic.severity,
4370                        is_unnecessary: entry.diagnostic.is_unnecessary,
4371                    });
4372                }
4373                diagnostic_endpoints
4374                    .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
4375                *diagnostics = diagnostic_endpoints.into_iter().peekable();
4376                self.hint_depth = 0;
4377                self.error_depth = 0;
4378                self.warning_depth = 0;
4379                self.information_depth = 0;
4380            }
4381        }
4382    }
4383
4384    /// The current byte offset in the buffer.
4385    pub fn offset(&self) -> usize {
4386        self.range.start
4387    }
4388
4389    pub fn range(&self) -> Range<usize> {
4390        self.range.clone()
4391    }
4392
4393    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
4394        let depth = match endpoint.severity {
4395            DiagnosticSeverity::ERROR => &mut self.error_depth,
4396            DiagnosticSeverity::WARNING => &mut self.warning_depth,
4397            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
4398            DiagnosticSeverity::HINT => &mut self.hint_depth,
4399            _ => return,
4400        };
4401        if endpoint.is_start {
4402            *depth += 1;
4403        } else {
4404            *depth -= 1;
4405        }
4406
4407        if endpoint.is_unnecessary {
4408            if endpoint.is_start {
4409                self.unnecessary_depth += 1;
4410            } else {
4411                self.unnecessary_depth -= 1;
4412            }
4413        }
4414    }
4415
4416    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
4417        if self.error_depth > 0 {
4418            Some(DiagnosticSeverity::ERROR)
4419        } else if self.warning_depth > 0 {
4420            Some(DiagnosticSeverity::WARNING)
4421        } else if self.information_depth > 0 {
4422            Some(DiagnosticSeverity::INFORMATION)
4423        } else if self.hint_depth > 0 {
4424            Some(DiagnosticSeverity::HINT)
4425        } else {
4426            None
4427        }
4428    }
4429
4430    fn current_code_is_unnecessary(&self) -> bool {
4431        self.unnecessary_depth > 0
4432    }
4433}
4434
4435impl<'a> Iterator for BufferChunks<'a> {
4436    type Item = Chunk<'a>;
4437
4438    fn next(&mut self) -> Option<Self::Item> {
4439        let mut next_capture_start = usize::MAX;
4440        let mut next_diagnostic_endpoint = usize::MAX;
4441
4442        if let Some(highlights) = self.highlights.as_mut() {
4443            while let Some((parent_capture_end, _)) = highlights.stack.last() {
4444                if *parent_capture_end <= self.range.start {
4445                    highlights.stack.pop();
4446                } else {
4447                    break;
4448                }
4449            }
4450
4451            if highlights.next_capture.is_none() {
4452                highlights.next_capture = highlights.captures.next();
4453            }
4454
4455            while let Some(capture) = highlights.next_capture.as_ref() {
4456                if self.range.start < capture.node.start_byte() {
4457                    next_capture_start = capture.node.start_byte();
4458                    break;
4459                } else {
4460                    let highlight_id =
4461                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
4462                    highlights
4463                        .stack
4464                        .push((capture.node.end_byte(), highlight_id));
4465                    highlights.next_capture = highlights.captures.next();
4466                }
4467            }
4468        }
4469
4470        let mut diagnostic_endpoints = std::mem::take(&mut self.diagnostic_endpoints);
4471        if let Some(diagnostic_endpoints) = diagnostic_endpoints.as_mut() {
4472            while let Some(endpoint) = diagnostic_endpoints.peek().copied() {
4473                if endpoint.offset <= self.range.start {
4474                    self.update_diagnostic_depths(endpoint);
4475                    diagnostic_endpoints.next();
4476                } else {
4477                    next_diagnostic_endpoint = endpoint.offset;
4478                    break;
4479                }
4480            }
4481        }
4482        self.diagnostic_endpoints = diagnostic_endpoints;
4483
4484        if let Some(chunk) = self.chunks.peek() {
4485            let chunk_start = self.range.start;
4486            let mut chunk_end = (self.chunks.offset() + chunk.len())
4487                .min(next_capture_start)
4488                .min(next_diagnostic_endpoint);
4489            let mut highlight_id = None;
4490            if let Some(highlights) = self.highlights.as_ref() {
4491                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
4492                    chunk_end = chunk_end.min(*parent_capture_end);
4493                    highlight_id = Some(*parent_highlight_id);
4494                }
4495            }
4496
4497            let slice =
4498                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
4499            self.range.start = chunk_end;
4500            if self.range.start == self.chunks.offset() + chunk.len() {
4501                self.chunks.next().unwrap();
4502            }
4503
4504            Some(Chunk {
4505                text: slice,
4506                syntax_highlight_id: highlight_id,
4507                diagnostic_severity: self.current_diagnostic_severity(),
4508                is_unnecessary: self.current_code_is_unnecessary(),
4509                ..Default::default()
4510            })
4511        } else {
4512            None
4513        }
4514    }
4515}
4516
4517impl operation_queue::Operation for Operation {
4518    fn lamport_timestamp(&self) -> clock::Lamport {
4519        match self {
4520            Operation::Buffer(_) => {
4521                unreachable!("buffer operations should never be deferred at this layer")
4522            }
4523            Operation::UpdateDiagnostics {
4524                lamport_timestamp, ..
4525            }
4526            | Operation::UpdateSelections {
4527                lamport_timestamp, ..
4528            }
4529            | Operation::UpdateCompletionTriggers {
4530                lamport_timestamp, ..
4531            } => *lamport_timestamp,
4532        }
4533    }
4534}
4535
4536impl Default for Diagnostic {
4537    fn default() -> Self {
4538        Self {
4539            source: Default::default(),
4540            code: None,
4541            severity: DiagnosticSeverity::ERROR,
4542            message: Default::default(),
4543            group_id: 0,
4544            is_primary: false,
4545            is_disk_based: false,
4546            is_unnecessary: false,
4547            data: None,
4548        }
4549    }
4550}
4551
4552impl IndentSize {
4553    /// Returns an [`IndentSize`] representing the given spaces.
4554    pub fn spaces(len: u32) -> Self {
4555        Self {
4556            len,
4557            kind: IndentKind::Space,
4558        }
4559    }
4560
4561    /// Returns an [`IndentSize`] representing a tab.
4562    pub fn tab() -> Self {
4563        Self {
4564            len: 1,
4565            kind: IndentKind::Tab,
4566        }
4567    }
4568
4569    /// An iterator over the characters represented by this [`IndentSize`].
4570    pub fn chars(&self) -> impl Iterator<Item = char> {
4571        iter::repeat(self.char()).take(self.len as usize)
4572    }
4573
4574    /// The character representation of this [`IndentSize`].
4575    pub fn char(&self) -> char {
4576        match self.kind {
4577            IndentKind::Space => ' ',
4578            IndentKind::Tab => '\t',
4579        }
4580    }
4581
4582    /// Consumes the current [`IndentSize`] and returns a new one that has
4583    /// been shrunk or enlarged by the given size along the given direction.
4584    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4585        match direction {
4586            Ordering::Less => {
4587                if self.kind == size.kind && self.len >= size.len {
4588                    self.len -= size.len;
4589                }
4590            }
4591            Ordering::Equal => {}
4592            Ordering::Greater => {
4593                if self.len == 0 {
4594                    self = size;
4595                } else if self.kind == size.kind {
4596                    self.len += size.len;
4597                }
4598            }
4599        }
4600        self
4601    }
4602
4603    pub fn len_with_expanded_tabs(&self, tab_size: NonZeroU32) -> usize {
4604        match self.kind {
4605            IndentKind::Space => self.len as usize,
4606            IndentKind::Tab => self.len as usize * tab_size.get() as usize,
4607        }
4608    }
4609}
4610
4611#[cfg(any(test, feature = "test-support"))]
4612pub struct TestFile {
4613    pub path: Arc<Path>,
4614    pub root_name: String,
4615    pub local_root: Option<PathBuf>,
4616}
4617
4618#[cfg(any(test, feature = "test-support"))]
4619impl File for TestFile {
4620    fn path(&self) -> &Arc<Path> {
4621        &self.path
4622    }
4623
4624    fn full_path(&self, _: &gpui::App) -> PathBuf {
4625        PathBuf::from(&self.root_name).join(self.path.as_ref())
4626    }
4627
4628    fn as_local(&self) -> Option<&dyn LocalFile> {
4629        if self.local_root.is_some() {
4630            Some(self)
4631        } else {
4632            None
4633        }
4634    }
4635
4636    fn disk_state(&self) -> DiskState {
4637        unimplemented!()
4638    }
4639
4640    fn file_name<'a>(&'a self, _: &'a gpui::App) -> &'a std::ffi::OsStr {
4641        self.path().file_name().unwrap_or(self.root_name.as_ref())
4642    }
4643
4644    fn worktree_id(&self, _: &App) -> WorktreeId {
4645        WorktreeId::from_usize(0)
4646    }
4647
4648    fn as_any(&self) -> &dyn std::any::Any {
4649        unimplemented!()
4650    }
4651
4652    fn to_proto(&self, _: &App) -> rpc::proto::File {
4653        unimplemented!()
4654    }
4655
4656    fn is_private(&self) -> bool {
4657        false
4658    }
4659}
4660
4661#[cfg(any(test, feature = "test-support"))]
4662impl LocalFile for TestFile {
4663    fn abs_path(&self, _cx: &App) -> PathBuf {
4664        PathBuf::from(self.local_root.as_ref().unwrap())
4665            .join(&self.root_name)
4666            .join(self.path.as_ref())
4667    }
4668
4669    fn load(&self, _cx: &App) -> Task<Result<String>> {
4670        unimplemented!()
4671    }
4672
4673    fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
4674        unimplemented!()
4675    }
4676}
4677
4678pub(crate) fn contiguous_ranges(
4679    values: impl Iterator<Item = u32>,
4680    max_len: usize,
4681) -> impl Iterator<Item = Range<u32>> {
4682    let mut values = values;
4683    let mut current_range: Option<Range<u32>> = None;
4684    std::iter::from_fn(move || {
4685        loop {
4686            if let Some(value) = values.next() {
4687                if let Some(range) = &mut current_range {
4688                    if value == range.end && range.len() < max_len {
4689                        range.end += 1;
4690                        continue;
4691                    }
4692                }
4693
4694                let prev_range = current_range.clone();
4695                current_range = Some(value..(value + 1));
4696                if prev_range.is_some() {
4697                    return prev_range;
4698                }
4699            } else {
4700                return current_range.take();
4701            }
4702        }
4703    })
4704}
4705
4706#[derive(Default, Debug)]
4707pub struct CharClassifier {
4708    scope: Option<LanguageScope>,
4709    for_completion: bool,
4710    ignore_punctuation: bool,
4711}
4712
4713impl CharClassifier {
4714    pub fn new(scope: Option<LanguageScope>) -> Self {
4715        Self {
4716            scope,
4717            for_completion: false,
4718            ignore_punctuation: false,
4719        }
4720    }
4721
4722    pub fn for_completion(self, for_completion: bool) -> Self {
4723        Self {
4724            for_completion,
4725            ..self
4726        }
4727    }
4728
4729    pub fn ignore_punctuation(self, ignore_punctuation: bool) -> Self {
4730        Self {
4731            ignore_punctuation,
4732            ..self
4733        }
4734    }
4735
4736    pub fn is_whitespace(&self, c: char) -> bool {
4737        self.kind(c) == CharKind::Whitespace
4738    }
4739
4740    pub fn is_word(&self, c: char) -> bool {
4741        self.kind(c) == CharKind::Word
4742    }
4743
4744    pub fn is_punctuation(&self, c: char) -> bool {
4745        self.kind(c) == CharKind::Punctuation
4746    }
4747
4748    pub fn kind_with(&self, c: char, ignore_punctuation: bool) -> CharKind {
4749        if c.is_alphanumeric() || c == '_' {
4750            return CharKind::Word;
4751        }
4752
4753        if let Some(scope) = &self.scope {
4754            let characters = if self.for_completion {
4755                scope.completion_query_characters()
4756            } else {
4757                scope.word_characters()
4758            };
4759            if let Some(characters) = characters {
4760                if characters.contains(&c) {
4761                    return CharKind::Word;
4762                }
4763            }
4764        }
4765
4766        if c.is_whitespace() {
4767            return CharKind::Whitespace;
4768        }
4769
4770        if ignore_punctuation {
4771            CharKind::Word
4772        } else {
4773            CharKind::Punctuation
4774        }
4775    }
4776
4777    pub fn kind(&self, c: char) -> CharKind {
4778        self.kind_with(c, self.ignore_punctuation)
4779    }
4780}
4781
4782/// Find all of the ranges of whitespace that occur at the ends of lines
4783/// in the given rope.
4784///
4785/// This could also be done with a regex search, but this implementation
4786/// avoids copying text.
4787pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4788    let mut ranges = Vec::new();
4789
4790    let mut offset = 0;
4791    let mut prev_chunk_trailing_whitespace_range = 0..0;
4792    for chunk in rope.chunks() {
4793        let mut prev_line_trailing_whitespace_range = 0..0;
4794        for (i, line) in chunk.split('\n').enumerate() {
4795            let line_end_offset = offset + line.len();
4796            let trimmed_line_len = line.trim_end_matches([' ', '\t']).len();
4797            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4798
4799            if i == 0 && trimmed_line_len == 0 {
4800                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4801            }
4802            if !prev_line_trailing_whitespace_range.is_empty() {
4803                ranges.push(prev_line_trailing_whitespace_range);
4804            }
4805
4806            offset = line_end_offset + 1;
4807            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4808        }
4809
4810        offset -= 1;
4811        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4812    }
4813
4814    if !prev_chunk_trailing_whitespace_range.is_empty() {
4815        ranges.push(prev_chunk_trailing_whitespace_range);
4816    }
4817
4818    ranges
4819}