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, true, 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    ///
1886    /// If `atomic` is true, the diff will be applied as a single edit.
1887    pub fn apply_diff(
1888        &mut self,
1889        diff: Diff,
1890        atomic: bool,
1891        cx: &mut Context<Self>,
1892    ) -> Option<TransactionId> {
1893        let snapshot = self.snapshot();
1894        let mut edits_since = snapshot.edits_since::<usize>(&diff.base_version).peekable();
1895        let mut delta = 0;
1896        let adjusted_edits = diff.edits.into_iter().filter_map(|(range, new_text)| {
1897            while let Some(edit_since) = edits_since.peek() {
1898                // If the edit occurs after a diff hunk, then it does not
1899                // affect that hunk.
1900                if edit_since.old.start > range.end {
1901                    break;
1902                }
1903                // If the edit precedes the diff hunk, then adjust the hunk
1904                // to reflect the edit.
1905                else if edit_since.old.end < range.start {
1906                    delta += edit_since.new_len() as i64 - edit_since.old_len() as i64;
1907                    edits_since.next();
1908                }
1909                // If the edit intersects a diff hunk, then discard that hunk.
1910                else {
1911                    return None;
1912                }
1913            }
1914
1915            let start = (range.start as i64 + delta) as usize;
1916            let end = (range.end as i64 + delta) as usize;
1917            Some((start..end, new_text))
1918        });
1919
1920        self.start_transaction();
1921        self.text.set_line_ending(diff.line_ending);
1922        if atomic {
1923            self.edit(adjusted_edits, None, cx);
1924        } else {
1925            let mut delta = 0isize;
1926            for (range, new_text) in adjusted_edits {
1927                let adjusted_range =
1928                    (range.start as isize + delta) as usize..(range.end as isize + delta) as usize;
1929                delta += new_text.len() as isize - range.len() as isize;
1930                self.edit([(adjusted_range, new_text)], None, cx);
1931            }
1932        }
1933        self.end_transaction(cx)
1934    }
1935
1936    fn has_unsaved_edits(&self) -> bool {
1937        let (last_version, has_unsaved_edits) = self.has_unsaved_edits.take();
1938
1939        if last_version == self.version {
1940            self.has_unsaved_edits
1941                .set((last_version, has_unsaved_edits));
1942            return has_unsaved_edits;
1943        }
1944
1945        let has_edits = self.has_edits_since(&self.saved_version);
1946        self.has_unsaved_edits
1947            .set((self.version.clone(), has_edits));
1948        has_edits
1949    }
1950
1951    /// Checks if the buffer has unsaved changes.
1952    pub fn is_dirty(&self) -> bool {
1953        if self.capability == Capability::ReadOnly {
1954            return false;
1955        }
1956        if self.has_conflict {
1957            return true;
1958        }
1959        match self.file.as_ref().map(|f| f.disk_state()) {
1960            Some(DiskState::New) | Some(DiskState::Deleted) => {
1961                !self.is_empty() && self.has_unsaved_edits()
1962            }
1963            _ => self.has_unsaved_edits(),
1964        }
1965    }
1966
1967    /// Checks if the buffer and its file have both changed since the buffer
1968    /// was last saved or reloaded.
1969    pub fn has_conflict(&self) -> bool {
1970        if self.has_conflict {
1971            return true;
1972        }
1973        let Some(file) = self.file.as_ref() else {
1974            return false;
1975        };
1976        match file.disk_state() {
1977            DiskState::New => false,
1978            DiskState::Present { mtime } => match self.saved_mtime {
1979                Some(saved_mtime) => {
1980                    mtime.bad_is_greater_than(saved_mtime) && self.has_unsaved_edits()
1981                }
1982                None => true,
1983            },
1984            DiskState::Deleted => false,
1985        }
1986    }
1987
1988    /// Gets a [`Subscription`] that tracks all of the changes to the buffer's text.
1989    pub fn subscribe(&mut self) -> Subscription {
1990        self.text.subscribe()
1991    }
1992
1993    /// Adds a bit to the list of bits that are set when the buffer's text changes.
1994    ///
1995    /// This allows downstream code to check if the buffer's text has changed without
1996    /// waiting for an effect cycle, which would be required if using eents.
1997    pub fn record_changes(&mut self, bit: rc::Weak<Cell<bool>>) {
1998        if let Err(ix) = self
1999            .change_bits
2000            .binary_search_by_key(&rc::Weak::as_ptr(&bit), rc::Weak::as_ptr)
2001        {
2002            self.change_bits.insert(ix, bit);
2003        }
2004    }
2005
2006    fn was_changed(&mut self) {
2007        self.change_bits.retain(|change_bit| {
2008            change_bit.upgrade().map_or(false, |bit| {
2009                bit.replace(true);
2010                true
2011            })
2012        });
2013    }
2014
2015    /// Starts a transaction, if one is not already in-progress. When undoing or
2016    /// redoing edits, all of the edits performed within a transaction are undone
2017    /// or redone together.
2018    pub fn start_transaction(&mut self) -> Option<TransactionId> {
2019        self.start_transaction_at(Instant::now())
2020    }
2021
2022    /// Starts a transaction, providing the current time. Subsequent transactions
2023    /// that occur within a short period of time will be grouped together. This
2024    /// is controlled by the buffer's undo grouping duration.
2025    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
2026        self.transaction_depth += 1;
2027        if self.was_dirty_before_starting_transaction.is_none() {
2028            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
2029        }
2030        self.text.start_transaction_at(now)
2031    }
2032
2033    /// Terminates the current transaction, if this is the outermost transaction.
2034    pub fn end_transaction(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2035        self.end_transaction_at(Instant::now(), cx)
2036    }
2037
2038    /// Terminates the current transaction, providing the current time. Subsequent transactions
2039    /// that occur within a short period of time will be grouped together. This
2040    /// is controlled by the buffer's undo grouping duration.
2041    pub fn end_transaction_at(
2042        &mut self,
2043        now: Instant,
2044        cx: &mut Context<Self>,
2045    ) -> Option<TransactionId> {
2046        assert!(self.transaction_depth > 0);
2047        self.transaction_depth -= 1;
2048        let was_dirty = if self.transaction_depth == 0 {
2049            self.was_dirty_before_starting_transaction.take().unwrap()
2050        } else {
2051            false
2052        };
2053        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
2054            self.did_edit(&start_version, was_dirty, cx);
2055            Some(transaction_id)
2056        } else {
2057            None
2058        }
2059    }
2060
2061    /// Manually add a transaction to the buffer's undo history.
2062    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
2063        self.text.push_transaction(transaction, now);
2064    }
2065
2066    /// Prevent the last transaction from being grouped with any subsequent transactions,
2067    /// even if they occur with the buffer's undo grouping duration.
2068    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
2069        self.text.finalize_last_transaction()
2070    }
2071
2072    /// Manually group all changes since a given transaction.
2073    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
2074        self.text.group_until_transaction(transaction_id);
2075    }
2076
2077    /// Manually remove a transaction from the buffer's undo history
2078    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
2079        self.text.forget_transaction(transaction_id);
2080    }
2081
2082    /// Manually merge two adjacent transactions in the buffer's undo history.
2083    pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
2084        self.text.merge_transactions(transaction, destination);
2085    }
2086
2087    /// Waits for the buffer to receive operations with the given timestamps.
2088    pub fn wait_for_edits<It: IntoIterator<Item = clock::Lamport>>(
2089        &mut self,
2090        edit_ids: It,
2091    ) -> impl Future<Output = Result<()>> + use<It> {
2092        self.text.wait_for_edits(edit_ids)
2093    }
2094
2095    /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
2096    pub fn wait_for_anchors<It: IntoIterator<Item = Anchor>>(
2097        &mut self,
2098        anchors: It,
2099    ) -> impl 'static + Future<Output = Result<()>> + use<It> {
2100        self.text.wait_for_anchors(anchors)
2101    }
2102
2103    /// Waits for the buffer to receive operations up to the given version.
2104    pub fn wait_for_version(
2105        &mut self,
2106        version: clock::Global,
2107    ) -> impl Future<Output = Result<()>> + use<> {
2108        self.text.wait_for_version(version)
2109    }
2110
2111    /// Forces all futures returned by [`Buffer::wait_for_version`], [`Buffer::wait_for_edits`], or
2112    /// [`Buffer::wait_for_version`] to resolve with an error.
2113    pub fn give_up_waiting(&mut self) {
2114        self.text.give_up_waiting();
2115    }
2116
2117    /// Stores a set of selections that should be broadcasted to all of the buffer's replicas.
2118    pub fn set_active_selections(
2119        &mut self,
2120        selections: Arc<[Selection<Anchor>]>,
2121        line_mode: bool,
2122        cursor_shape: CursorShape,
2123        cx: &mut Context<Self>,
2124    ) {
2125        let lamport_timestamp = self.text.lamport_clock.tick();
2126        self.remote_selections.insert(
2127            self.text.replica_id(),
2128            SelectionSet {
2129                selections: selections.clone(),
2130                lamport_timestamp,
2131                line_mode,
2132                cursor_shape,
2133            },
2134        );
2135        self.send_operation(
2136            Operation::UpdateSelections {
2137                selections,
2138                line_mode,
2139                lamport_timestamp,
2140                cursor_shape,
2141            },
2142            true,
2143            cx,
2144        );
2145        self.non_text_state_update_count += 1;
2146        cx.notify();
2147    }
2148
2149    /// Clears the selections, so that other replicas of the buffer do not see any selections for
2150    /// this replica.
2151    pub fn remove_active_selections(&mut self, cx: &mut Context<Self>) {
2152        if self
2153            .remote_selections
2154            .get(&self.text.replica_id())
2155            .map_or(true, |set| !set.selections.is_empty())
2156        {
2157            self.set_active_selections(Arc::default(), false, Default::default(), cx);
2158        }
2159    }
2160
2161    /// Replaces the buffer's entire text.
2162    pub fn set_text<T>(&mut self, text: T, cx: &mut Context<Self>) -> Option<clock::Lamport>
2163    where
2164        T: Into<Arc<str>>,
2165    {
2166        self.autoindent_requests.clear();
2167        self.edit([(0..self.len(), text)], None, cx)
2168    }
2169
2170    /// Applies the given edits to the buffer. Each edit is specified as a range of text to
2171    /// delete, and a string of text to insert at that location.
2172    ///
2173    /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
2174    /// request for the edited ranges, which will be processed when the buffer finishes
2175    /// parsing.
2176    ///
2177    /// Parsing takes place at the end of a transaction, and may compute synchronously
2178    /// or asynchronously, depending on the changes.
2179    pub fn edit<I, S, T>(
2180        &mut self,
2181        edits_iter: I,
2182        autoindent_mode: Option<AutoindentMode>,
2183        cx: &mut Context<Self>,
2184    ) -> Option<clock::Lamport>
2185    where
2186        I: IntoIterator<Item = (Range<S>, T)>,
2187        S: ToOffset,
2188        T: Into<Arc<str>>,
2189    {
2190        // Skip invalid edits and coalesce contiguous ones.
2191        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
2192
2193        for (range, new_text) in edits_iter {
2194            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2195
2196            if range.start > range.end {
2197                mem::swap(&mut range.start, &mut range.end);
2198            }
2199            let new_text = new_text.into();
2200            if !new_text.is_empty() || !range.is_empty() {
2201                if let Some((prev_range, prev_text)) = edits.last_mut() {
2202                    if prev_range.end >= range.start {
2203                        prev_range.end = cmp::max(prev_range.end, range.end);
2204                        *prev_text = format!("{prev_text}{new_text}").into();
2205                    } else {
2206                        edits.push((range, new_text));
2207                    }
2208                } else {
2209                    edits.push((range, new_text));
2210                }
2211            }
2212        }
2213        if edits.is_empty() {
2214            return None;
2215        }
2216
2217        self.start_transaction();
2218        self.pending_autoindent.take();
2219        let autoindent_request = autoindent_mode
2220            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
2221
2222        let edit_operation = self.text.edit(edits.iter().cloned());
2223        let edit_id = edit_operation.timestamp();
2224
2225        if let Some((before_edit, mode)) = autoindent_request {
2226            let mut delta = 0isize;
2227            let entries = edits
2228                .into_iter()
2229                .enumerate()
2230                .zip(&edit_operation.as_edit().unwrap().new_text)
2231                .map(|((ix, (range, _)), new_text)| {
2232                    let new_text_length = new_text.len();
2233                    let old_start = range.start.to_point(&before_edit);
2234                    let new_start = (delta + range.start as isize) as usize;
2235                    let range_len = range.end - range.start;
2236                    delta += new_text_length as isize - range_len as isize;
2237
2238                    // Decide what range of the insertion to auto-indent, and whether
2239                    // the first line of the insertion should be considered a newly-inserted line
2240                    // or an edit to an existing line.
2241                    let mut range_of_insertion_to_indent = 0..new_text_length;
2242                    let mut first_line_is_new = true;
2243
2244                    let old_line_start = before_edit.indent_size_for_line(old_start.row).len;
2245                    let old_line_end = before_edit.line_len(old_start.row);
2246
2247                    if old_start.column > old_line_start {
2248                        first_line_is_new = false;
2249                    }
2250
2251                    if !new_text.contains('\n')
2252                        && (old_start.column + (range_len as u32) < old_line_end
2253                            || old_line_end == old_line_start)
2254                    {
2255                        first_line_is_new = false;
2256                    }
2257
2258                    // When inserting text starting with a newline, avoid auto-indenting the
2259                    // previous line.
2260                    if new_text.starts_with('\n') {
2261                        range_of_insertion_to_indent.start += 1;
2262                        first_line_is_new = true;
2263                    }
2264
2265                    let mut original_indent_column = None;
2266                    if let AutoindentMode::Block {
2267                        original_indent_columns,
2268                    } = &mode
2269                    {
2270                        original_indent_column = Some(
2271                            original_indent_columns
2272                                .get(ix)
2273                                .copied()
2274                                .flatten()
2275                                .unwrap_or_else(|| {
2276                                    indent_size_for_text(
2277                                        new_text[range_of_insertion_to_indent.clone()].chars(),
2278                                    )
2279                                    .len
2280                                }),
2281                        );
2282
2283                        // Avoid auto-indenting the line after the edit.
2284                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
2285                            range_of_insertion_to_indent.end -= 1;
2286                        }
2287                    }
2288
2289                    AutoindentRequestEntry {
2290                        first_line_is_new,
2291                        original_indent_column,
2292                        indent_size: before_edit.language_indent_size_at(range.start, cx),
2293                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
2294                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
2295                    }
2296                })
2297                .collect();
2298
2299            self.autoindent_requests.push(Arc::new(AutoindentRequest {
2300                before_edit,
2301                entries,
2302                is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
2303                ignore_empty_lines: false,
2304            }));
2305        }
2306
2307        self.end_transaction(cx);
2308        self.send_operation(Operation::Buffer(edit_operation), true, cx);
2309        Some(edit_id)
2310    }
2311
2312    fn did_edit(&mut self, old_version: &clock::Global, was_dirty: bool, cx: &mut Context<Self>) {
2313        self.was_changed();
2314
2315        if self.edits_since::<usize>(old_version).next().is_none() {
2316            return;
2317        }
2318
2319        self.reparse(cx);
2320        cx.emit(BufferEvent::Edited);
2321        if was_dirty != self.is_dirty() {
2322            cx.emit(BufferEvent::DirtyChanged);
2323        }
2324        cx.notify();
2325    }
2326
2327    pub fn autoindent_ranges<I, T>(&mut self, ranges: I, cx: &mut Context<Self>)
2328    where
2329        I: IntoIterator<Item = Range<T>>,
2330        T: ToOffset + Copy,
2331    {
2332        let before_edit = self.snapshot();
2333        let entries = ranges
2334            .into_iter()
2335            .map(|range| AutoindentRequestEntry {
2336                range: before_edit.anchor_before(range.start)..before_edit.anchor_after(range.end),
2337                first_line_is_new: true,
2338                indent_size: before_edit.language_indent_size_at(range.start, cx),
2339                original_indent_column: None,
2340            })
2341            .collect();
2342        self.autoindent_requests.push(Arc::new(AutoindentRequest {
2343            before_edit,
2344            entries,
2345            is_block_mode: false,
2346            ignore_empty_lines: true,
2347        }));
2348        self.request_autoindent(cx);
2349    }
2350
2351    // Inserts newlines at the given position to create an empty line, returning the start of the new line.
2352    // You can also request the insertion of empty lines above and below the line starting at the returned point.
2353    pub fn insert_empty_line(
2354        &mut self,
2355        position: impl ToPoint,
2356        space_above: bool,
2357        space_below: bool,
2358        cx: &mut Context<Self>,
2359    ) -> Point {
2360        let mut position = position.to_point(self);
2361
2362        self.start_transaction();
2363
2364        self.edit(
2365            [(position..position, "\n")],
2366            Some(AutoindentMode::EachLine),
2367            cx,
2368        );
2369
2370        if position.column > 0 {
2371            position += Point::new(1, 0);
2372        }
2373
2374        if !self.is_line_blank(position.row) {
2375            self.edit(
2376                [(position..position, "\n")],
2377                Some(AutoindentMode::EachLine),
2378                cx,
2379            );
2380        }
2381
2382        if space_above && position.row > 0 && !self.is_line_blank(position.row - 1) {
2383            self.edit(
2384                [(position..position, "\n")],
2385                Some(AutoindentMode::EachLine),
2386                cx,
2387            );
2388            position.row += 1;
2389        }
2390
2391        if space_below
2392            && (position.row == self.max_point().row || !self.is_line_blank(position.row + 1))
2393        {
2394            self.edit(
2395                [(position..position, "\n")],
2396                Some(AutoindentMode::EachLine),
2397                cx,
2398            );
2399        }
2400
2401        self.end_transaction(cx);
2402
2403        position
2404    }
2405
2406    /// Applies the given remote operations to the buffer.
2407    pub fn apply_ops<I: IntoIterator<Item = Operation>>(&mut self, ops: I, cx: &mut Context<Self>) {
2408        self.pending_autoindent.take();
2409        let was_dirty = self.is_dirty();
2410        let old_version = self.version.clone();
2411        let mut deferred_ops = Vec::new();
2412        let buffer_ops = ops
2413            .into_iter()
2414            .filter_map(|op| match op {
2415                Operation::Buffer(op) => Some(op),
2416                _ => {
2417                    if self.can_apply_op(&op) {
2418                        self.apply_op(op, cx);
2419                    } else {
2420                        deferred_ops.push(op);
2421                    }
2422                    None
2423                }
2424            })
2425            .collect::<Vec<_>>();
2426        for operation in buffer_ops.iter() {
2427            self.send_operation(Operation::Buffer(operation.clone()), false, cx);
2428        }
2429        self.text.apply_ops(buffer_ops);
2430        self.deferred_ops.insert(deferred_ops);
2431        self.flush_deferred_ops(cx);
2432        self.did_edit(&old_version, was_dirty, cx);
2433        // Notify independently of whether the buffer was edited as the operations could include a
2434        // selection update.
2435        cx.notify();
2436    }
2437
2438    fn flush_deferred_ops(&mut self, cx: &mut Context<Self>) {
2439        let mut deferred_ops = Vec::new();
2440        for op in self.deferred_ops.drain().iter().cloned() {
2441            if self.can_apply_op(&op) {
2442                self.apply_op(op, cx);
2443            } else {
2444                deferred_ops.push(op);
2445            }
2446        }
2447        self.deferred_ops.insert(deferred_ops);
2448    }
2449
2450    pub fn has_deferred_ops(&self) -> bool {
2451        !self.deferred_ops.is_empty() || self.text.has_deferred_ops()
2452    }
2453
2454    fn can_apply_op(&self, operation: &Operation) -> bool {
2455        match operation {
2456            Operation::Buffer(_) => {
2457                unreachable!("buffer operations should never be applied at this layer")
2458            }
2459            Operation::UpdateDiagnostics {
2460                diagnostics: diagnostic_set,
2461                ..
2462            } => diagnostic_set.iter().all(|diagnostic| {
2463                self.text.can_resolve(&diagnostic.range.start)
2464                    && self.text.can_resolve(&diagnostic.range.end)
2465            }),
2466            Operation::UpdateSelections { selections, .. } => selections
2467                .iter()
2468                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
2469            Operation::UpdateCompletionTriggers { .. } => true,
2470        }
2471    }
2472
2473    fn apply_op(&mut self, operation: Operation, cx: &mut Context<Self>) {
2474        match operation {
2475            Operation::Buffer(_) => {
2476                unreachable!("buffer operations should never be applied at this layer")
2477            }
2478            Operation::UpdateDiagnostics {
2479                server_id,
2480                diagnostics: diagnostic_set,
2481                lamport_timestamp,
2482            } => {
2483                let snapshot = self.snapshot();
2484                self.apply_diagnostic_update(
2485                    server_id,
2486                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
2487                    lamport_timestamp,
2488                    cx,
2489                );
2490            }
2491            Operation::UpdateSelections {
2492                selections,
2493                lamport_timestamp,
2494                line_mode,
2495                cursor_shape,
2496            } => {
2497                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
2498                    if set.lamport_timestamp > lamport_timestamp {
2499                        return;
2500                    }
2501                }
2502
2503                self.remote_selections.insert(
2504                    lamport_timestamp.replica_id,
2505                    SelectionSet {
2506                        selections,
2507                        lamport_timestamp,
2508                        line_mode,
2509                        cursor_shape,
2510                    },
2511                );
2512                self.text.lamport_clock.observe(lamport_timestamp);
2513                self.non_text_state_update_count += 1;
2514            }
2515            Operation::UpdateCompletionTriggers {
2516                triggers,
2517                lamport_timestamp,
2518                server_id,
2519            } => {
2520                if triggers.is_empty() {
2521                    self.completion_triggers_per_language_server
2522                        .remove(&server_id);
2523                    self.completion_triggers = self
2524                        .completion_triggers_per_language_server
2525                        .values()
2526                        .flat_map(|triggers| triggers.into_iter().cloned())
2527                        .collect();
2528                } else {
2529                    self.completion_triggers_per_language_server
2530                        .insert(server_id, triggers.iter().cloned().collect());
2531                    self.completion_triggers.extend(triggers);
2532                }
2533                self.text.lamport_clock.observe(lamport_timestamp);
2534            }
2535        }
2536    }
2537
2538    fn apply_diagnostic_update(
2539        &mut self,
2540        server_id: LanguageServerId,
2541        diagnostics: DiagnosticSet,
2542        lamport_timestamp: clock::Lamport,
2543        cx: &mut Context<Self>,
2544    ) {
2545        if lamport_timestamp > self.diagnostics_timestamp {
2546            let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
2547            if diagnostics.is_empty() {
2548                if let Ok(ix) = ix {
2549                    self.diagnostics.remove(ix);
2550                }
2551            } else {
2552                match ix {
2553                    Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
2554                    Ok(ix) => self.diagnostics[ix].1 = diagnostics,
2555                };
2556            }
2557            self.diagnostics_timestamp = lamport_timestamp;
2558            self.non_text_state_update_count += 1;
2559            self.text.lamport_clock.observe(lamport_timestamp);
2560            cx.notify();
2561            cx.emit(BufferEvent::DiagnosticsUpdated);
2562        }
2563    }
2564
2565    fn send_operation(&mut self, operation: Operation, is_local: bool, cx: &mut Context<Self>) {
2566        self.was_changed();
2567        cx.emit(BufferEvent::Operation {
2568            operation,
2569            is_local,
2570        });
2571    }
2572
2573    /// Removes the selections for a given peer.
2574    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut Context<Self>) {
2575        self.remote_selections.remove(&replica_id);
2576        cx.notify();
2577    }
2578
2579    /// Undoes the most recent transaction.
2580    pub fn undo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2581        let was_dirty = self.is_dirty();
2582        let old_version = self.version.clone();
2583
2584        if let Some((transaction_id, operation)) = self.text.undo() {
2585            self.send_operation(Operation::Buffer(operation), true, cx);
2586            self.did_edit(&old_version, was_dirty, cx);
2587            Some(transaction_id)
2588        } else {
2589            None
2590        }
2591    }
2592
2593    /// Manually undoes a specific transaction in the buffer's undo history.
2594    pub fn undo_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        if let Some(operation) = self.text.undo_transaction(transaction_id) {
2602            self.send_operation(Operation::Buffer(operation), true, cx);
2603            self.did_edit(&old_version, was_dirty, cx);
2604            true
2605        } else {
2606            false
2607        }
2608    }
2609
2610    /// Manually undoes all changes after a given transaction in the buffer's undo history.
2611    pub fn undo_to_transaction(
2612        &mut self,
2613        transaction_id: TransactionId,
2614        cx: &mut Context<Self>,
2615    ) -> bool {
2616        let was_dirty = self.is_dirty();
2617        let old_version = self.version.clone();
2618
2619        let operations = self.text.undo_to_transaction(transaction_id);
2620        let undone = !operations.is_empty();
2621        for operation in operations {
2622            self.send_operation(Operation::Buffer(operation), true, cx);
2623        }
2624        if undone {
2625            self.did_edit(&old_version, was_dirty, cx)
2626        }
2627        undone
2628    }
2629
2630    pub fn undo_operations(&mut self, counts: HashMap<Lamport, u32>, cx: &mut Context<Buffer>) {
2631        let was_dirty = self.is_dirty();
2632        let operation = self.text.undo_operations(counts);
2633        let old_version = self.version.clone();
2634        self.send_operation(Operation::Buffer(operation), true, cx);
2635        self.did_edit(&old_version, was_dirty, cx);
2636    }
2637
2638    /// Manually redoes a specific transaction in the buffer's redo history.
2639    pub fn redo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2640        let was_dirty = self.is_dirty();
2641        let old_version = self.version.clone();
2642
2643        if let Some((transaction_id, operation)) = self.text.redo() {
2644            self.send_operation(Operation::Buffer(operation), true, cx);
2645            self.did_edit(&old_version, was_dirty, cx);
2646            Some(transaction_id)
2647        } else {
2648            None
2649        }
2650    }
2651
2652    /// Manually undoes all changes until a given transaction in the buffer's redo history.
2653    pub fn redo_to_transaction(
2654        &mut self,
2655        transaction_id: TransactionId,
2656        cx: &mut Context<Self>,
2657    ) -> bool {
2658        let was_dirty = self.is_dirty();
2659        let old_version = self.version.clone();
2660
2661        let operations = self.text.redo_to_transaction(transaction_id);
2662        let redone = !operations.is_empty();
2663        for operation in operations {
2664            self.send_operation(Operation::Buffer(operation), true, cx);
2665        }
2666        if redone {
2667            self.did_edit(&old_version, was_dirty, cx)
2668        }
2669        redone
2670    }
2671
2672    /// Override current completion triggers with the user-provided completion triggers.
2673    pub fn set_completion_triggers(
2674        &mut self,
2675        server_id: LanguageServerId,
2676        triggers: BTreeSet<String>,
2677        cx: &mut Context<Self>,
2678    ) {
2679        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2680        if triggers.is_empty() {
2681            self.completion_triggers_per_language_server
2682                .remove(&server_id);
2683            self.completion_triggers = self
2684                .completion_triggers_per_language_server
2685                .values()
2686                .flat_map(|triggers| triggers.into_iter().cloned())
2687                .collect();
2688        } else {
2689            self.completion_triggers_per_language_server
2690                .insert(server_id, triggers.clone());
2691            self.completion_triggers.extend(triggers.iter().cloned());
2692        }
2693        self.send_operation(
2694            Operation::UpdateCompletionTriggers {
2695                triggers: triggers.iter().cloned().collect(),
2696                lamport_timestamp: self.completion_triggers_timestamp,
2697                server_id,
2698            },
2699            true,
2700            cx,
2701        );
2702        cx.notify();
2703    }
2704
2705    /// Returns a list of strings which trigger a completion menu for this language.
2706    /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2707    pub fn completion_triggers(&self) -> &BTreeSet<String> {
2708        &self.completion_triggers
2709    }
2710
2711    /// Call this directly after performing edits to prevent the preview tab
2712    /// from being dismissed by those edits. It causes `should_dismiss_preview`
2713    /// to return false until there are additional edits.
2714    pub fn refresh_preview(&mut self) {
2715        self.preview_version = self.version.clone();
2716    }
2717
2718    /// Whether we should preserve the preview status of a tab containing this buffer.
2719    pub fn preserve_preview(&self) -> bool {
2720        !self.has_edits_since(&self.preview_version)
2721    }
2722}
2723
2724#[doc(hidden)]
2725#[cfg(any(test, feature = "test-support"))]
2726impl Buffer {
2727    pub fn edit_via_marked_text(
2728        &mut self,
2729        marked_string: &str,
2730        autoindent_mode: Option<AutoindentMode>,
2731        cx: &mut Context<Self>,
2732    ) {
2733        let edits = self.edits_for_marked_text(marked_string);
2734        self.edit(edits, autoindent_mode, cx);
2735    }
2736
2737    pub fn set_group_interval(&mut self, group_interval: Duration) {
2738        self.text.set_group_interval(group_interval);
2739    }
2740
2741    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize, cx: &mut Context<Self>)
2742    where
2743        T: rand::Rng,
2744    {
2745        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2746        let mut last_end = None;
2747        for _ in 0..old_range_count {
2748            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2749                break;
2750            }
2751
2752            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2753            let mut range = self.random_byte_range(new_start, rng);
2754            if rng.gen_bool(0.2) {
2755                mem::swap(&mut range.start, &mut range.end);
2756            }
2757            last_end = Some(range.end);
2758
2759            let new_text_len = rng.gen_range(0..10);
2760            let mut new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2761            new_text = new_text.to_uppercase();
2762
2763            edits.push((range, new_text));
2764        }
2765        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2766        self.edit(edits, None, cx);
2767    }
2768
2769    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut Context<Self>) {
2770        let was_dirty = self.is_dirty();
2771        let old_version = self.version.clone();
2772
2773        let ops = self.text.randomly_undo_redo(rng);
2774        if !ops.is_empty() {
2775            for op in ops {
2776                self.send_operation(Operation::Buffer(op), true, cx);
2777                self.did_edit(&old_version, was_dirty, cx);
2778            }
2779        }
2780    }
2781}
2782
2783impl EventEmitter<BufferEvent> for Buffer {}
2784
2785impl Deref for Buffer {
2786    type Target = TextBuffer;
2787
2788    fn deref(&self) -> &Self::Target {
2789        &self.text
2790    }
2791}
2792
2793impl BufferSnapshot {
2794    /// Returns [`IndentSize`] for a given line that respects user settings and
2795    /// language preferences.
2796    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2797        indent_size_for_line(self, row)
2798    }
2799
2800    /// Returns [`IndentSize`] for a given position that respects user settings
2801    /// and language preferences.
2802    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &App) -> IndentSize {
2803        let settings = language_settings(
2804            self.language_at(position).map(|l| l.name()),
2805            self.file(),
2806            cx,
2807        );
2808        if settings.hard_tabs {
2809            IndentSize::tab()
2810        } else {
2811            IndentSize::spaces(settings.tab_size.get())
2812        }
2813    }
2814
2815    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2816    /// is passed in as `single_indent_size`.
2817    pub fn suggested_indents(
2818        &self,
2819        rows: impl Iterator<Item = u32>,
2820        single_indent_size: IndentSize,
2821    ) -> BTreeMap<u32, IndentSize> {
2822        let mut result = BTreeMap::new();
2823
2824        for row_range in contiguous_ranges(rows, 10) {
2825            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2826                Some(suggestions) => suggestions,
2827                _ => break,
2828            };
2829
2830            for (row, suggestion) in row_range.zip(suggestions) {
2831                let indent_size = if let Some(suggestion) = suggestion {
2832                    result
2833                        .get(&suggestion.basis_row)
2834                        .copied()
2835                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2836                        .with_delta(suggestion.delta, single_indent_size)
2837                } else {
2838                    self.indent_size_for_line(row)
2839                };
2840
2841                result.insert(row, indent_size);
2842            }
2843        }
2844
2845        result
2846    }
2847
2848    fn suggest_autoindents(
2849        &self,
2850        row_range: Range<u32>,
2851    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2852        let config = &self.language.as_ref()?.config;
2853        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2854
2855        // Find the suggested indentation ranges based on the syntax tree.
2856        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2857        let end = Point::new(row_range.end, 0);
2858        let range = (start..end).to_offset(&self.text);
2859        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2860            Some(&grammar.indents_config.as_ref()?.query)
2861        });
2862        let indent_configs = matches
2863            .grammars()
2864            .iter()
2865            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2866            .collect::<Vec<_>>();
2867
2868        let mut indent_ranges = Vec::<Range<Point>>::new();
2869        let mut outdent_positions = Vec::<Point>::new();
2870        while let Some(mat) = matches.peek() {
2871            let mut start: Option<Point> = None;
2872            let mut end: Option<Point> = None;
2873
2874            let config = &indent_configs[mat.grammar_index];
2875            for capture in mat.captures {
2876                if capture.index == config.indent_capture_ix {
2877                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2878                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2879                } else if Some(capture.index) == config.start_capture_ix {
2880                    start = Some(Point::from_ts_point(capture.node.end_position()));
2881                } else if Some(capture.index) == config.end_capture_ix {
2882                    end = Some(Point::from_ts_point(capture.node.start_position()));
2883                } else if Some(capture.index) == config.outdent_capture_ix {
2884                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2885                }
2886            }
2887
2888            matches.advance();
2889            if let Some((start, end)) = start.zip(end) {
2890                if start.row == end.row {
2891                    continue;
2892                }
2893
2894                let range = start..end;
2895                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2896                    Err(ix) => indent_ranges.insert(ix, range),
2897                    Ok(ix) => {
2898                        let prev_range = &mut indent_ranges[ix];
2899                        prev_range.end = prev_range.end.max(range.end);
2900                    }
2901                }
2902            }
2903        }
2904
2905        let mut error_ranges = Vec::<Range<Point>>::new();
2906        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2907            grammar.error_query.as_ref()
2908        });
2909        while let Some(mat) = matches.peek() {
2910            let node = mat.captures[0].node;
2911            let start = Point::from_ts_point(node.start_position());
2912            let end = Point::from_ts_point(node.end_position());
2913            let range = start..end;
2914            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2915                Ok(ix) | Err(ix) => ix,
2916            };
2917            let mut end_ix = ix;
2918            while let Some(existing_range) = error_ranges.get(end_ix) {
2919                if existing_range.end < end {
2920                    end_ix += 1;
2921                } else {
2922                    break;
2923                }
2924            }
2925            error_ranges.splice(ix..end_ix, [range]);
2926            matches.advance();
2927        }
2928
2929        outdent_positions.sort();
2930        for outdent_position in outdent_positions {
2931            // find the innermost indent range containing this outdent_position
2932            // set its end to the outdent position
2933            if let Some(range_to_truncate) = indent_ranges
2934                .iter_mut()
2935                .filter(|indent_range| indent_range.contains(&outdent_position))
2936                .last()
2937            {
2938                range_to_truncate.end = outdent_position;
2939            }
2940        }
2941
2942        // Find the suggested indentation increases and decreased based on regexes.
2943        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2944        self.for_each_line(
2945            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2946                ..Point::new(row_range.end, 0),
2947            |row, line| {
2948                if config
2949                    .decrease_indent_pattern
2950                    .as_ref()
2951                    .map_or(false, |regex| regex.is_match(line))
2952                {
2953                    indent_change_rows.push((row, Ordering::Less));
2954                }
2955                if config
2956                    .increase_indent_pattern
2957                    .as_ref()
2958                    .map_or(false, |regex| regex.is_match(line))
2959                {
2960                    indent_change_rows.push((row + 1, Ordering::Greater));
2961                }
2962            },
2963        );
2964
2965        let mut indent_changes = indent_change_rows.into_iter().peekable();
2966        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2967            prev_non_blank_row.unwrap_or(0)
2968        } else {
2969            row_range.start.saturating_sub(1)
2970        };
2971        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2972        Some(row_range.map(move |row| {
2973            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2974
2975            let mut indent_from_prev_row = false;
2976            let mut outdent_from_prev_row = false;
2977            let mut outdent_to_row = u32::MAX;
2978            let mut from_regex = false;
2979
2980            while let Some((indent_row, delta)) = indent_changes.peek() {
2981                match indent_row.cmp(&row) {
2982                    Ordering::Equal => match delta {
2983                        Ordering::Less => {
2984                            from_regex = true;
2985                            outdent_from_prev_row = true
2986                        }
2987                        Ordering::Greater => {
2988                            indent_from_prev_row = true;
2989                            from_regex = true
2990                        }
2991                        _ => {}
2992                    },
2993
2994                    Ordering::Greater => break,
2995                    Ordering::Less => {}
2996                }
2997
2998                indent_changes.next();
2999            }
3000
3001            for range in &indent_ranges {
3002                if range.start.row >= row {
3003                    break;
3004                }
3005                if range.start.row == prev_row && range.end > row_start {
3006                    indent_from_prev_row = true;
3007                }
3008                if range.end > prev_row_start && range.end <= row_start {
3009                    outdent_to_row = outdent_to_row.min(range.start.row);
3010                }
3011            }
3012
3013            let within_error = error_ranges
3014                .iter()
3015                .any(|e| e.start.row < row && e.end > row_start);
3016
3017            let suggestion = if outdent_to_row == prev_row
3018                || (outdent_from_prev_row && indent_from_prev_row)
3019            {
3020                Some(IndentSuggestion {
3021                    basis_row: prev_row,
3022                    delta: Ordering::Equal,
3023                    within_error: within_error && !from_regex,
3024                })
3025            } else if indent_from_prev_row {
3026                Some(IndentSuggestion {
3027                    basis_row: prev_row,
3028                    delta: Ordering::Greater,
3029                    within_error: within_error && !from_regex,
3030                })
3031            } else if outdent_to_row < prev_row {
3032                Some(IndentSuggestion {
3033                    basis_row: outdent_to_row,
3034                    delta: Ordering::Equal,
3035                    within_error: within_error && !from_regex,
3036                })
3037            } else if outdent_from_prev_row {
3038                Some(IndentSuggestion {
3039                    basis_row: prev_row,
3040                    delta: Ordering::Less,
3041                    within_error: within_error && !from_regex,
3042                })
3043            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
3044            {
3045                Some(IndentSuggestion {
3046                    basis_row: prev_row,
3047                    delta: Ordering::Equal,
3048                    within_error: within_error && !from_regex,
3049                })
3050            } else {
3051                None
3052            };
3053
3054            prev_row = row;
3055            prev_row_start = row_start;
3056            suggestion
3057        }))
3058    }
3059
3060    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
3061        while row > 0 {
3062            row -= 1;
3063            if !self.is_line_blank(row) {
3064                return Some(row);
3065            }
3066        }
3067        None
3068    }
3069
3070    fn get_highlights(&self, range: Range<usize>) -> (SyntaxMapCaptures, Vec<HighlightMap>) {
3071        let captures = self.syntax.captures(range, &self.text, |grammar| {
3072            grammar.highlights_query.as_ref()
3073        });
3074        let highlight_maps = captures
3075            .grammars()
3076            .iter()
3077            .map(|grammar| grammar.highlight_map())
3078            .collect();
3079        (captures, highlight_maps)
3080    }
3081
3082    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
3083    /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
3084    /// returned in chunks where each chunk has a single syntax highlighting style and
3085    /// diagnostic status.
3086    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
3087        let range = range.start.to_offset(self)..range.end.to_offset(self);
3088
3089        let mut syntax = None;
3090        if language_aware {
3091            syntax = Some(self.get_highlights(range.clone()));
3092        }
3093        // We want to look at diagnostic spans only when iterating over language-annotated chunks.
3094        let diagnostics = language_aware;
3095        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostics, Some(self))
3096    }
3097
3098    pub fn highlighted_text_for_range<T: ToOffset>(
3099        &self,
3100        range: Range<T>,
3101        override_style: Option<HighlightStyle>,
3102        syntax_theme: &SyntaxTheme,
3103    ) -> HighlightedText {
3104        HighlightedText::from_buffer_range(
3105            range,
3106            &self.text,
3107            &self.syntax,
3108            override_style,
3109            syntax_theme,
3110        )
3111    }
3112
3113    /// Invokes the given callback for each line of text in the given range of the buffer.
3114    /// Uses callback to avoid allocating a string for each line.
3115    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
3116        let mut line = String::new();
3117        let mut row = range.start.row;
3118        for chunk in self
3119            .as_rope()
3120            .chunks_in_range(range.to_offset(self))
3121            .chain(["\n"])
3122        {
3123            for (newline_ix, text) in chunk.split('\n').enumerate() {
3124                if newline_ix > 0 {
3125                    callback(row, &line);
3126                    row += 1;
3127                    line.clear();
3128                }
3129                line.push_str(text);
3130            }
3131        }
3132    }
3133
3134    /// Iterates over every [`SyntaxLayer`] in the buffer.
3135    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
3136        self.syntax
3137            .layers_for_range(0..self.len(), &self.text, true)
3138    }
3139
3140    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
3141        let offset = position.to_offset(self);
3142        self.syntax
3143            .layers_for_range(offset..offset, &self.text, false)
3144            .filter(|l| l.node().end_byte() > offset)
3145            .last()
3146    }
3147
3148    pub fn smallest_syntax_layer_containing<D: ToOffset>(
3149        &self,
3150        range: Range<D>,
3151    ) -> Option<SyntaxLayer> {
3152        let range = range.to_offset(self);
3153        return self
3154            .syntax
3155            .layers_for_range(range, &self.text, false)
3156            .max_by(|a, b| {
3157                if a.depth != b.depth {
3158                    a.depth.cmp(&b.depth)
3159                } else if a.offset.0 != b.offset.0 {
3160                    a.offset.0.cmp(&b.offset.0)
3161                } else {
3162                    a.node().end_byte().cmp(&b.node().end_byte()).reverse()
3163                }
3164            });
3165    }
3166
3167    /// Returns the main [`Language`].
3168    pub fn language(&self) -> Option<&Arc<Language>> {
3169        self.language.as_ref()
3170    }
3171
3172    /// Returns the [`Language`] at the given location.
3173    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
3174        self.syntax_layer_at(position)
3175            .map(|info| info.language)
3176            .or(self.language.as_ref())
3177    }
3178
3179    /// Returns the settings for the language at the given location.
3180    pub fn settings_at<'a, D: ToOffset>(
3181        &'a self,
3182        position: D,
3183        cx: &'a App,
3184    ) -> Cow<'a, LanguageSettings> {
3185        language_settings(
3186            self.language_at(position).map(|l| l.name()),
3187            self.file.as_ref(),
3188            cx,
3189        )
3190    }
3191
3192    pub fn char_classifier_at<T: ToOffset>(&self, point: T) -> CharClassifier {
3193        CharClassifier::new(self.language_scope_at(point))
3194    }
3195
3196    /// Returns the [`LanguageScope`] at the given location.
3197    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
3198        let offset = position.to_offset(self);
3199        let mut scope = None;
3200        let mut smallest_range: Option<Range<usize>> = None;
3201
3202        // Use the layer that has the smallest node intersecting the given point.
3203        for layer in self
3204            .syntax
3205            .layers_for_range(offset..offset, &self.text, false)
3206        {
3207            let mut cursor = layer.node().walk();
3208
3209            let mut range = None;
3210            loop {
3211                let child_range = cursor.node().byte_range();
3212                if !child_range.to_inclusive().contains(&offset) {
3213                    break;
3214                }
3215
3216                range = Some(child_range);
3217                if cursor.goto_first_child_for_byte(offset).is_none() {
3218                    break;
3219                }
3220            }
3221
3222            if let Some(range) = range {
3223                if smallest_range
3224                    .as_ref()
3225                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
3226                {
3227                    smallest_range = Some(range);
3228                    scope = Some(LanguageScope {
3229                        language: layer.language.clone(),
3230                        override_id: layer.override_id(offset, &self.text),
3231                    });
3232                }
3233            }
3234        }
3235
3236        scope.or_else(|| {
3237            self.language.clone().map(|language| LanguageScope {
3238                language,
3239                override_id: None,
3240            })
3241        })
3242    }
3243
3244    /// Returns a tuple of the range and character kind of the word
3245    /// surrounding the given position.
3246    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
3247        let mut start = start.to_offset(self);
3248        let mut end = start;
3249        let mut next_chars = self.chars_at(start).peekable();
3250        let mut prev_chars = self.reversed_chars_at(start).peekable();
3251
3252        let classifier = self.char_classifier_at(start);
3253        let word_kind = cmp::max(
3254            prev_chars.peek().copied().map(|c| classifier.kind(c)),
3255            next_chars.peek().copied().map(|c| classifier.kind(c)),
3256        );
3257
3258        for ch in prev_chars {
3259            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3260                start -= ch.len_utf8();
3261            } else {
3262                break;
3263            }
3264        }
3265
3266        for ch in next_chars {
3267            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3268                end += ch.len_utf8();
3269            } else {
3270                break;
3271            }
3272        }
3273
3274        (start..end, word_kind)
3275    }
3276
3277    /// Returns the closest syntax node enclosing the given range.
3278    pub fn syntax_ancestor<'a, T: ToOffset>(
3279        &'a self,
3280        range: Range<T>,
3281    ) -> Option<tree_sitter::Node<'a>> {
3282        let range = range.start.to_offset(self)..range.end.to_offset(self);
3283        let mut result: Option<tree_sitter::Node<'a>> = None;
3284        'outer: for layer in self
3285            .syntax
3286            .layers_for_range(range.clone(), &self.text, true)
3287        {
3288            let mut cursor = layer.node().walk();
3289
3290            // Descend to the first leaf that touches the start of the range,
3291            // and if the range is non-empty, extends beyond the start.
3292            while cursor.goto_first_child_for_byte(range.start).is_some() {
3293                if !range.is_empty() && cursor.node().end_byte() == range.start {
3294                    cursor.goto_next_sibling();
3295                }
3296            }
3297
3298            // Ascend to the smallest ancestor that strictly contains the range.
3299            loop {
3300                let node_range = cursor.node().byte_range();
3301                if node_range.start <= range.start
3302                    && node_range.end >= range.end
3303                    && node_range.len() > range.len()
3304                {
3305                    break;
3306                }
3307                if !cursor.goto_parent() {
3308                    continue 'outer;
3309                }
3310            }
3311
3312            let left_node = cursor.node();
3313            let mut layer_result = left_node;
3314
3315            // For an empty range, try to find another node immediately to the right of the range.
3316            if left_node.end_byte() == range.start {
3317                let mut right_node = None;
3318                while !cursor.goto_next_sibling() {
3319                    if !cursor.goto_parent() {
3320                        break;
3321                    }
3322                }
3323
3324                while cursor.node().start_byte() == range.start {
3325                    right_node = Some(cursor.node());
3326                    if !cursor.goto_first_child() {
3327                        break;
3328                    }
3329                }
3330
3331                // If there is a candidate node on both sides of the (empty) range, then
3332                // decide between the two by favoring a named node over an anonymous token.
3333                // If both nodes are the same in that regard, favor the right one.
3334                if let Some(right_node) = right_node {
3335                    if right_node.is_named() || !left_node.is_named() {
3336                        layer_result = right_node;
3337                    }
3338                }
3339            }
3340
3341            if let Some(previous_result) = &result {
3342                if previous_result.byte_range().len() < layer_result.byte_range().len() {
3343                    continue;
3344                }
3345            }
3346            result = Some(layer_result);
3347        }
3348
3349        result
3350    }
3351
3352    /// Returns the outline for the buffer.
3353    ///
3354    /// This method allows passing an optional [`SyntaxTheme`] to
3355    /// syntax-highlight the returned symbols.
3356    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3357        self.outline_items_containing(0..self.len(), true, theme)
3358            .map(Outline::new)
3359    }
3360
3361    /// Returns all the symbols that contain the given position.
3362    ///
3363    /// This method allows passing an optional [`SyntaxTheme`] to
3364    /// syntax-highlight the returned symbols.
3365    pub fn symbols_containing<T: ToOffset>(
3366        &self,
3367        position: T,
3368        theme: Option<&SyntaxTheme>,
3369    ) -> Option<Vec<OutlineItem<Anchor>>> {
3370        let position = position.to_offset(self);
3371        let mut items = self.outline_items_containing(
3372            position.saturating_sub(1)..self.len().min(position + 1),
3373            false,
3374            theme,
3375        )?;
3376        let mut prev_depth = None;
3377        items.retain(|item| {
3378            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
3379            prev_depth = Some(item.depth);
3380            result
3381        });
3382        Some(items)
3383    }
3384
3385    pub fn outline_range_containing<T: ToOffset>(&self, range: Range<T>) -> Option<Range<Point>> {
3386        let range = range.to_offset(self);
3387        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3388            grammar.outline_config.as_ref().map(|c| &c.query)
3389        });
3390        let configs = matches
3391            .grammars()
3392            .iter()
3393            .map(|g| g.outline_config.as_ref().unwrap())
3394            .collect::<Vec<_>>();
3395
3396        while let Some(mat) = matches.peek() {
3397            let config = &configs[mat.grammar_index];
3398            let containing_item_node = maybe!({
3399                let item_node = mat.captures.iter().find_map(|cap| {
3400                    if cap.index == config.item_capture_ix {
3401                        Some(cap.node)
3402                    } else {
3403                        None
3404                    }
3405                })?;
3406
3407                let item_byte_range = item_node.byte_range();
3408                if item_byte_range.end < range.start || item_byte_range.start > range.end {
3409                    None
3410                } else {
3411                    Some(item_node)
3412                }
3413            });
3414
3415            if let Some(item_node) = containing_item_node {
3416                return Some(
3417                    Point::from_ts_point(item_node.start_position())
3418                        ..Point::from_ts_point(item_node.end_position()),
3419                );
3420            }
3421
3422            matches.advance();
3423        }
3424        None
3425    }
3426
3427    pub fn outline_items_containing<T: ToOffset>(
3428        &self,
3429        range: Range<T>,
3430        include_extra_context: bool,
3431        theme: Option<&SyntaxTheme>,
3432    ) -> Option<Vec<OutlineItem<Anchor>>> {
3433        let range = range.to_offset(self);
3434        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3435            grammar.outline_config.as_ref().map(|c| &c.query)
3436        });
3437        let configs = matches
3438            .grammars()
3439            .iter()
3440            .map(|g| g.outline_config.as_ref().unwrap())
3441            .collect::<Vec<_>>();
3442
3443        let mut items = Vec::new();
3444        let mut annotation_row_ranges: Vec<Range<u32>> = Vec::new();
3445        while let Some(mat) = matches.peek() {
3446            let config = &configs[mat.grammar_index];
3447            if let Some(item) =
3448                self.next_outline_item(config, &mat, &range, include_extra_context, theme)
3449            {
3450                items.push(item);
3451            } else if let Some(capture) = mat
3452                .captures
3453                .iter()
3454                .find(|capture| Some(capture.index) == config.annotation_capture_ix)
3455            {
3456                let capture_range = capture.node.start_position()..capture.node.end_position();
3457                let mut capture_row_range =
3458                    capture_range.start.row as u32..capture_range.end.row as u32;
3459                if capture_range.end.row > capture_range.start.row && capture_range.end.column == 0
3460                {
3461                    capture_row_range.end -= 1;
3462                }
3463                if let Some(last_row_range) = annotation_row_ranges.last_mut() {
3464                    if last_row_range.end >= capture_row_range.start.saturating_sub(1) {
3465                        last_row_range.end = capture_row_range.end;
3466                    } else {
3467                        annotation_row_ranges.push(capture_row_range);
3468                    }
3469                } else {
3470                    annotation_row_ranges.push(capture_row_range);
3471                }
3472            }
3473            matches.advance();
3474        }
3475
3476        items.sort_by_key(|item| (item.range.start, Reverse(item.range.end)));
3477
3478        // Assign depths based on containment relationships and convert to anchors.
3479        let mut item_ends_stack = Vec::<Point>::new();
3480        let mut anchor_items = Vec::new();
3481        let mut annotation_row_ranges = annotation_row_ranges.into_iter().peekable();
3482        for item in items {
3483            while let Some(last_end) = item_ends_stack.last().copied() {
3484                if last_end < item.range.end {
3485                    item_ends_stack.pop();
3486                } else {
3487                    break;
3488                }
3489            }
3490
3491            let mut annotation_row_range = None;
3492            while let Some(next_annotation_row_range) = annotation_row_ranges.peek() {
3493                let row_preceding_item = item.range.start.row.saturating_sub(1);
3494                if next_annotation_row_range.end < row_preceding_item {
3495                    annotation_row_ranges.next();
3496                } else {
3497                    if next_annotation_row_range.end == row_preceding_item {
3498                        annotation_row_range = Some(next_annotation_row_range.clone());
3499                        annotation_row_ranges.next();
3500                    }
3501                    break;
3502                }
3503            }
3504
3505            anchor_items.push(OutlineItem {
3506                depth: item_ends_stack.len(),
3507                range: self.anchor_after(item.range.start)..self.anchor_before(item.range.end),
3508                text: item.text,
3509                highlight_ranges: item.highlight_ranges,
3510                name_ranges: item.name_ranges,
3511                body_range: item.body_range.map(|body_range| {
3512                    self.anchor_after(body_range.start)..self.anchor_before(body_range.end)
3513                }),
3514                annotation_range: annotation_row_range.map(|annotation_range| {
3515                    self.anchor_after(Point::new(annotation_range.start, 0))
3516                        ..self.anchor_before(Point::new(
3517                            annotation_range.end,
3518                            self.line_len(annotation_range.end),
3519                        ))
3520                }),
3521            });
3522            item_ends_stack.push(item.range.end);
3523        }
3524
3525        Some(anchor_items)
3526    }
3527
3528    fn next_outline_item(
3529        &self,
3530        config: &OutlineConfig,
3531        mat: &SyntaxMapMatch,
3532        range: &Range<usize>,
3533        include_extra_context: bool,
3534        theme: Option<&SyntaxTheme>,
3535    ) -> Option<OutlineItem<Point>> {
3536        let item_node = mat.captures.iter().find_map(|cap| {
3537            if cap.index == config.item_capture_ix {
3538                Some(cap.node)
3539            } else {
3540                None
3541            }
3542        })?;
3543
3544        let item_byte_range = item_node.byte_range();
3545        if item_byte_range.end < range.start || item_byte_range.start > range.end {
3546            return None;
3547        }
3548        let item_point_range = Point::from_ts_point(item_node.start_position())
3549            ..Point::from_ts_point(item_node.end_position());
3550
3551        let mut open_point = None;
3552        let mut close_point = None;
3553        let mut buffer_ranges = Vec::new();
3554        for capture in mat.captures {
3555            let node_is_name;
3556            if capture.index == config.name_capture_ix {
3557                node_is_name = true;
3558            } else if Some(capture.index) == config.context_capture_ix
3559                || (Some(capture.index) == config.extra_context_capture_ix && include_extra_context)
3560            {
3561                node_is_name = false;
3562            } else {
3563                if Some(capture.index) == config.open_capture_ix {
3564                    open_point = Some(Point::from_ts_point(capture.node.end_position()));
3565                } else if Some(capture.index) == config.close_capture_ix {
3566                    close_point = Some(Point::from_ts_point(capture.node.start_position()));
3567                }
3568
3569                continue;
3570            }
3571
3572            let mut range = capture.node.start_byte()..capture.node.end_byte();
3573            let start = capture.node.start_position();
3574            if capture.node.end_position().row > start.row {
3575                range.end = range.start + self.line_len(start.row as u32) as usize - start.column;
3576            }
3577
3578            if !range.is_empty() {
3579                buffer_ranges.push((range, node_is_name));
3580            }
3581        }
3582        if buffer_ranges.is_empty() {
3583            return None;
3584        }
3585        let mut text = String::new();
3586        let mut highlight_ranges = Vec::new();
3587        let mut name_ranges = Vec::new();
3588        let mut chunks = self.chunks(
3589            buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
3590            true,
3591        );
3592        let mut last_buffer_range_end = 0;
3593
3594        for (buffer_range, is_name) in buffer_ranges {
3595            let space_added = !text.is_empty() && buffer_range.start > last_buffer_range_end;
3596            if space_added {
3597                text.push(' ');
3598            }
3599            let before_append_len = text.len();
3600            let mut offset = buffer_range.start;
3601            chunks.seek(buffer_range.clone());
3602            for mut chunk in chunks.by_ref() {
3603                if chunk.text.len() > buffer_range.end - offset {
3604                    chunk.text = &chunk.text[0..(buffer_range.end - offset)];
3605                    offset = buffer_range.end;
3606                } else {
3607                    offset += chunk.text.len();
3608                }
3609                let style = chunk
3610                    .syntax_highlight_id
3611                    .zip(theme)
3612                    .and_then(|(highlight, theme)| highlight.style(theme));
3613                if let Some(style) = style {
3614                    let start = text.len();
3615                    let end = start + chunk.text.len();
3616                    highlight_ranges.push((start..end, style));
3617                }
3618                text.push_str(chunk.text);
3619                if offset >= buffer_range.end {
3620                    break;
3621                }
3622            }
3623            if is_name {
3624                let after_append_len = text.len();
3625                let start = if space_added && !name_ranges.is_empty() {
3626                    before_append_len - 1
3627                } else {
3628                    before_append_len
3629                };
3630                name_ranges.push(start..after_append_len);
3631            }
3632            last_buffer_range_end = buffer_range.end;
3633        }
3634
3635        Some(OutlineItem {
3636            depth: 0, // We'll calculate the depth later
3637            range: item_point_range,
3638            text,
3639            highlight_ranges,
3640            name_ranges,
3641            body_range: open_point.zip(close_point).map(|(start, end)| start..end),
3642            annotation_range: None,
3643        })
3644    }
3645
3646    pub fn function_body_fold_ranges<T: ToOffset>(
3647        &self,
3648        within: Range<T>,
3649    ) -> impl Iterator<Item = Range<usize>> + '_ {
3650        self.text_object_ranges(within, TreeSitterOptions::default())
3651            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
3652    }
3653
3654    /// For each grammar in the language, runs the provided
3655    /// [`tree_sitter::Query`] against the given range.
3656    pub fn matches(
3657        &self,
3658        range: Range<usize>,
3659        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
3660    ) -> SyntaxMapMatches {
3661        self.syntax.matches(range, self, query)
3662    }
3663
3664    pub fn all_bracket_ranges(
3665        &self,
3666        range: Range<usize>,
3667    ) -> impl Iterator<Item = BracketMatch> + '_ {
3668        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3669            grammar.brackets_config.as_ref().map(|c| &c.query)
3670        });
3671        let configs = matches
3672            .grammars()
3673            .iter()
3674            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
3675            .collect::<Vec<_>>();
3676
3677        iter::from_fn(move || {
3678            while let Some(mat) = matches.peek() {
3679                let mut open = None;
3680                let mut close = None;
3681                let config = &configs[mat.grammar_index];
3682                let pattern = &config.patterns[mat.pattern_index];
3683                for capture in mat.captures {
3684                    if capture.index == config.open_capture_ix {
3685                        open = Some(capture.node.byte_range());
3686                    } else if capture.index == config.close_capture_ix {
3687                        close = Some(capture.node.byte_range());
3688                    }
3689                }
3690
3691                matches.advance();
3692
3693                let Some((open_range, close_range)) = open.zip(close) else {
3694                    continue;
3695                };
3696
3697                let bracket_range = open_range.start..=close_range.end;
3698                if !bracket_range.overlaps(&range) {
3699                    continue;
3700                }
3701
3702                return Some(BracketMatch {
3703                    open_range,
3704                    close_range,
3705                    newline_only: pattern.newline_only,
3706                });
3707            }
3708            None
3709        })
3710    }
3711
3712    /// Returns bracket range pairs overlapping or adjacent to `range`
3713    pub fn bracket_ranges<T: ToOffset>(
3714        &self,
3715        range: Range<T>,
3716    ) -> impl Iterator<Item = BracketMatch> + '_ {
3717        // Find bracket pairs that *inclusively* contain the given range.
3718        let range = range.start.to_offset(self).saturating_sub(1)
3719            ..self.len().min(range.end.to_offset(self) + 1);
3720        self.all_bracket_ranges(range)
3721            .filter(|pair| !pair.newline_only)
3722    }
3723
3724    pub fn text_object_ranges<T: ToOffset>(
3725        &self,
3726        range: Range<T>,
3727        options: TreeSitterOptions,
3728    ) -> impl Iterator<Item = (Range<usize>, TextObject)> + '_ {
3729        let range = range.start.to_offset(self).saturating_sub(1)
3730            ..self.len().min(range.end.to_offset(self) + 1);
3731
3732        let mut matches =
3733            self.syntax
3734                .matches_with_options(range.clone(), &self.text, options, |grammar| {
3735                    grammar.text_object_config.as_ref().map(|c| &c.query)
3736                });
3737
3738        let configs = matches
3739            .grammars()
3740            .iter()
3741            .map(|grammar| grammar.text_object_config.as_ref())
3742            .collect::<Vec<_>>();
3743
3744        let mut captures = Vec::<(Range<usize>, TextObject)>::new();
3745
3746        iter::from_fn(move || {
3747            loop {
3748                while let Some(capture) = captures.pop() {
3749                    if capture.0.overlaps(&range) {
3750                        return Some(capture);
3751                    }
3752                }
3753
3754                let mat = matches.peek()?;
3755
3756                let Some(config) = configs[mat.grammar_index].as_ref() else {
3757                    matches.advance();
3758                    continue;
3759                };
3760
3761                for capture in mat.captures {
3762                    let Some(ix) = config
3763                        .text_objects_by_capture_ix
3764                        .binary_search_by_key(&capture.index, |e| e.0)
3765                        .ok()
3766                    else {
3767                        continue;
3768                    };
3769                    let text_object = config.text_objects_by_capture_ix[ix].1;
3770                    let byte_range = capture.node.byte_range();
3771
3772                    let mut found = false;
3773                    for (range, existing) in captures.iter_mut() {
3774                        if existing == &text_object {
3775                            range.start = range.start.min(byte_range.start);
3776                            range.end = range.end.max(byte_range.end);
3777                            found = true;
3778                            break;
3779                        }
3780                    }
3781
3782                    if !found {
3783                        captures.push((byte_range, text_object));
3784                    }
3785                }
3786
3787                matches.advance();
3788            }
3789        })
3790    }
3791
3792    /// Returns enclosing bracket ranges containing the given range
3793    pub fn enclosing_bracket_ranges<T: ToOffset>(
3794        &self,
3795        range: Range<T>,
3796    ) -> impl Iterator<Item = BracketMatch> + '_ {
3797        let range = range.start.to_offset(self)..range.end.to_offset(self);
3798
3799        self.bracket_ranges(range.clone()).filter(move |pair| {
3800            pair.open_range.start <= range.start && pair.close_range.end >= range.end
3801        })
3802    }
3803
3804    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3805    ///
3806    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3807    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3808        &self,
3809        range: Range<T>,
3810        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3811    ) -> Option<(Range<usize>, Range<usize>)> {
3812        let range = range.start.to_offset(self)..range.end.to_offset(self);
3813
3814        // Get the ranges of the innermost pair of brackets.
3815        let mut result: Option<(Range<usize>, Range<usize>)> = None;
3816
3817        for pair in self.enclosing_bracket_ranges(range.clone()) {
3818            if let Some(range_filter) = range_filter {
3819                if !range_filter(pair.open_range.clone(), pair.close_range.clone()) {
3820                    continue;
3821                }
3822            }
3823
3824            let len = pair.close_range.end - pair.open_range.start;
3825
3826            if let Some((existing_open, existing_close)) = &result {
3827                let existing_len = existing_close.end - existing_open.start;
3828                if len > existing_len {
3829                    continue;
3830                }
3831            }
3832
3833            result = Some((pair.open_range, pair.close_range));
3834        }
3835
3836        result
3837    }
3838
3839    /// Returns anchor ranges for any matches of the redaction query.
3840    /// The buffer can be associated with multiple languages, and the redaction query associated with each
3841    /// will be run on the relevant section of the buffer.
3842    pub fn redacted_ranges<T: ToOffset>(
3843        &self,
3844        range: Range<T>,
3845    ) -> impl Iterator<Item = Range<usize>> + '_ {
3846        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3847        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3848            grammar
3849                .redactions_config
3850                .as_ref()
3851                .map(|config| &config.query)
3852        });
3853
3854        let configs = syntax_matches
3855            .grammars()
3856            .iter()
3857            .map(|grammar| grammar.redactions_config.as_ref())
3858            .collect::<Vec<_>>();
3859
3860        iter::from_fn(move || {
3861            let redacted_range = syntax_matches
3862                .peek()
3863                .and_then(|mat| {
3864                    configs[mat.grammar_index].and_then(|config| {
3865                        mat.captures
3866                            .iter()
3867                            .find(|capture| capture.index == config.redaction_capture_ix)
3868                    })
3869                })
3870                .map(|mat| mat.node.byte_range());
3871            syntax_matches.advance();
3872            redacted_range
3873        })
3874    }
3875
3876    pub fn injections_intersecting_range<T: ToOffset>(
3877        &self,
3878        range: Range<T>,
3879    ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3880        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3881
3882        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3883            grammar
3884                .injection_config
3885                .as_ref()
3886                .map(|config| &config.query)
3887        });
3888
3889        let configs = syntax_matches
3890            .grammars()
3891            .iter()
3892            .map(|grammar| grammar.injection_config.as_ref())
3893            .collect::<Vec<_>>();
3894
3895        iter::from_fn(move || {
3896            let ranges = syntax_matches.peek().and_then(|mat| {
3897                let config = &configs[mat.grammar_index]?;
3898                let content_capture_range = mat.captures.iter().find_map(|capture| {
3899                    if capture.index == config.content_capture_ix {
3900                        Some(capture.node.byte_range())
3901                    } else {
3902                        None
3903                    }
3904                })?;
3905                let language = self.language_at(content_capture_range.start)?;
3906                Some((content_capture_range, language))
3907            });
3908            syntax_matches.advance();
3909            ranges
3910        })
3911    }
3912
3913    pub fn runnable_ranges(
3914        &self,
3915        offset_range: Range<usize>,
3916    ) -> impl Iterator<Item = RunnableRange> + '_ {
3917        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3918            grammar.runnable_config.as_ref().map(|config| &config.query)
3919        });
3920
3921        let test_configs = syntax_matches
3922            .grammars()
3923            .iter()
3924            .map(|grammar| grammar.runnable_config.as_ref())
3925            .collect::<Vec<_>>();
3926
3927        iter::from_fn(move || {
3928            loop {
3929                let mat = syntax_matches.peek()?;
3930
3931                let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3932                    let mut run_range = None;
3933                    let full_range = mat.captures.iter().fold(
3934                        Range {
3935                            start: usize::MAX,
3936                            end: 0,
3937                        },
3938                        |mut acc, next| {
3939                            let byte_range = next.node.byte_range();
3940                            if acc.start > byte_range.start {
3941                                acc.start = byte_range.start;
3942                            }
3943                            if acc.end < byte_range.end {
3944                                acc.end = byte_range.end;
3945                            }
3946                            acc
3947                        },
3948                    );
3949                    if full_range.start > full_range.end {
3950                        // We did not find a full spanning range of this match.
3951                        return None;
3952                    }
3953                    let extra_captures: SmallVec<[_; 1]> =
3954                        SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3955                            test_configs
3956                                .extra_captures
3957                                .get(capture.index as usize)
3958                                .cloned()
3959                                .and_then(|tag_name| match tag_name {
3960                                    RunnableCapture::Named(name) => {
3961                                        Some((capture.node.byte_range(), name))
3962                                    }
3963                                    RunnableCapture::Run => {
3964                                        let _ = run_range.insert(capture.node.byte_range());
3965                                        None
3966                                    }
3967                                })
3968                        }));
3969                    let run_range = run_range?;
3970                    let tags = test_configs
3971                        .query
3972                        .property_settings(mat.pattern_index)
3973                        .iter()
3974                        .filter_map(|property| {
3975                            if *property.key == *"tag" {
3976                                property
3977                                    .value
3978                                    .as_ref()
3979                                    .map(|value| RunnableTag(value.to_string().into()))
3980                            } else {
3981                                None
3982                            }
3983                        })
3984                        .collect();
3985                    let extra_captures = extra_captures
3986                        .into_iter()
3987                        .map(|(range, name)| {
3988                            (
3989                                name.to_string(),
3990                                self.text_for_range(range.clone()).collect::<String>(),
3991                            )
3992                        })
3993                        .collect();
3994                    // All tags should have the same range.
3995                    Some(RunnableRange {
3996                        run_range,
3997                        full_range,
3998                        runnable: Runnable {
3999                            tags,
4000                            language: mat.language,
4001                            buffer: self.remote_id(),
4002                        },
4003                        extra_captures,
4004                        buffer_id: self.remote_id(),
4005                    })
4006                });
4007
4008                syntax_matches.advance();
4009                if test_range.is_some() {
4010                    // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
4011                    // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
4012                    return test_range;
4013                }
4014            }
4015        })
4016    }
4017
4018    /// Returns selections for remote peers intersecting the given range.
4019    #[allow(clippy::type_complexity)]
4020    pub fn selections_in_range(
4021        &self,
4022        range: Range<Anchor>,
4023        include_local: bool,
4024    ) -> impl Iterator<
4025        Item = (
4026            ReplicaId,
4027            bool,
4028            CursorShape,
4029            impl Iterator<Item = &Selection<Anchor>> + '_,
4030        ),
4031    > + '_ {
4032        self.remote_selections
4033            .iter()
4034            .filter(move |(replica_id, set)| {
4035                (include_local || **replica_id != self.text.replica_id())
4036                    && !set.selections.is_empty()
4037            })
4038            .map(move |(replica_id, set)| {
4039                let start_ix = match set.selections.binary_search_by(|probe| {
4040                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
4041                }) {
4042                    Ok(ix) | Err(ix) => ix,
4043                };
4044                let end_ix = match set.selections.binary_search_by(|probe| {
4045                    probe.start.cmp(&range.end, self).then(Ordering::Less)
4046                }) {
4047                    Ok(ix) | Err(ix) => ix,
4048                };
4049
4050                (
4051                    *replica_id,
4052                    set.line_mode,
4053                    set.cursor_shape,
4054                    set.selections[start_ix..end_ix].iter(),
4055                )
4056            })
4057    }
4058
4059    /// Returns if the buffer contains any diagnostics.
4060    pub fn has_diagnostics(&self) -> bool {
4061        !self.diagnostics.is_empty()
4062    }
4063
4064    /// Returns all the diagnostics intersecting the given range.
4065    pub fn diagnostics_in_range<'a, T, O>(
4066        &'a self,
4067        search_range: Range<T>,
4068        reversed: bool,
4069    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
4070    where
4071        T: 'a + Clone + ToOffset,
4072        O: 'a + FromAnchor,
4073    {
4074        let mut iterators: Vec<_> = self
4075            .diagnostics
4076            .iter()
4077            .map(|(_, collection)| {
4078                collection
4079                    .range::<T, text::Anchor>(search_range.clone(), self, true, reversed)
4080                    .peekable()
4081            })
4082            .collect();
4083
4084        std::iter::from_fn(move || {
4085            let (next_ix, _) = iterators
4086                .iter_mut()
4087                .enumerate()
4088                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
4089                .min_by(|(_, a), (_, b)| {
4090                    let cmp = a
4091                        .range
4092                        .start
4093                        .cmp(&b.range.start, self)
4094                        // when range is equal, sort by diagnostic severity
4095                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
4096                        // and stabilize order with group_id
4097                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
4098                    if reversed { cmp.reverse() } else { cmp }
4099                })?;
4100            iterators[next_ix]
4101                .next()
4102                .map(|DiagnosticEntry { range, diagnostic }| DiagnosticEntry {
4103                    diagnostic,
4104                    range: FromAnchor::from_anchor(&range.start, self)
4105                        ..FromAnchor::from_anchor(&range.end, self),
4106                })
4107        })
4108    }
4109
4110    /// Returns all the diagnostic groups associated with the given
4111    /// language server ID. If no language server ID is provided,
4112    /// all diagnostics groups are returned.
4113    pub fn diagnostic_groups(
4114        &self,
4115        language_server_id: Option<LanguageServerId>,
4116    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
4117        let mut groups = Vec::new();
4118
4119        if let Some(language_server_id) = language_server_id {
4120            if let Ok(ix) = self
4121                .diagnostics
4122                .binary_search_by_key(&language_server_id, |e| e.0)
4123            {
4124                self.diagnostics[ix]
4125                    .1
4126                    .groups(language_server_id, &mut groups, self);
4127            }
4128        } else {
4129            for (language_server_id, diagnostics) in self.diagnostics.iter() {
4130                diagnostics.groups(*language_server_id, &mut groups, self);
4131            }
4132        }
4133
4134        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
4135            let a_start = &group_a.entries[group_a.primary_ix].range.start;
4136            let b_start = &group_b.entries[group_b.primary_ix].range.start;
4137            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
4138        });
4139
4140        groups
4141    }
4142
4143    /// Returns an iterator over the diagnostics for the given group.
4144    pub fn diagnostic_group<O>(
4145        &self,
4146        group_id: usize,
4147    ) -> impl Iterator<Item = DiagnosticEntry<O>> + '_
4148    where
4149        O: FromAnchor + 'static,
4150    {
4151        self.diagnostics
4152            .iter()
4153            .flat_map(move |(_, set)| set.group(group_id, self))
4154    }
4155
4156    /// An integer version number that accounts for all updates besides
4157    /// the buffer's text itself (which is versioned via a version vector).
4158    pub fn non_text_state_update_count(&self) -> usize {
4159        self.non_text_state_update_count
4160    }
4161
4162    /// Returns a snapshot of underlying file.
4163    pub fn file(&self) -> Option<&Arc<dyn File>> {
4164        self.file.as_ref()
4165    }
4166
4167    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
4168    pub fn resolve_file_path(&self, cx: &App, include_root: bool) -> Option<PathBuf> {
4169        if let Some(file) = self.file() {
4170            if file.path().file_name().is_none() || include_root {
4171                Some(file.full_path(cx))
4172            } else {
4173                Some(file.path().to_path_buf())
4174            }
4175        } else {
4176            None
4177        }
4178    }
4179
4180    pub fn words_in_range(&self, query: WordsQuery) -> HashMap<String, Range<Anchor>> {
4181        let query_str = query.fuzzy_contents;
4182        if query_str.map_or(false, |query| query.is_empty()) {
4183            return HashMap::default();
4184        }
4185
4186        let classifier = CharClassifier::new(self.language.clone().map(|language| LanguageScope {
4187            language,
4188            override_id: None,
4189        }));
4190
4191        let mut query_ix = 0;
4192        let query_chars = query_str.map(|query| query.chars().collect::<Vec<_>>());
4193        let query_len = query_chars.as_ref().map_or(0, |query| query.len());
4194
4195        let mut words = HashMap::default();
4196        let mut current_word_start_ix = None;
4197        let mut chunk_ix = query.range.start;
4198        for chunk in self.chunks(query.range, false) {
4199            for (i, c) in chunk.text.char_indices() {
4200                let ix = chunk_ix + i;
4201                if classifier.is_word(c) {
4202                    if current_word_start_ix.is_none() {
4203                        current_word_start_ix = Some(ix);
4204                    }
4205
4206                    if let Some(query_chars) = &query_chars {
4207                        if query_ix < query_len {
4208                            if c.to_lowercase().eq(query_chars[query_ix].to_lowercase()) {
4209                                query_ix += 1;
4210                            }
4211                        }
4212                    }
4213                    continue;
4214                } else if let Some(word_start) = current_word_start_ix.take() {
4215                    if query_ix == query_len {
4216                        let word_range = self.anchor_before(word_start)..self.anchor_after(ix);
4217                        let mut word_text = self.text_for_range(word_start..ix).peekable();
4218                        let first_char = word_text
4219                            .peek()
4220                            .and_then(|first_chunk| first_chunk.chars().next());
4221                        // Skip empty and "words" starting with digits as a heuristic to reduce useless completions
4222                        if !query.skip_digits
4223                            || first_char.map_or(true, |first_char| !first_char.is_digit(10))
4224                        {
4225                            words.insert(word_text.collect(), word_range);
4226                        }
4227                    }
4228                }
4229                query_ix = 0;
4230            }
4231            chunk_ix += chunk.text.len();
4232        }
4233
4234        words
4235    }
4236}
4237
4238pub struct WordsQuery<'a> {
4239    /// Only returns words with all chars from the fuzzy string in them.
4240    pub fuzzy_contents: Option<&'a str>,
4241    /// Skips words that start with a digit.
4242    pub skip_digits: bool,
4243    /// Buffer offset range, to look for words.
4244    pub range: Range<usize>,
4245}
4246
4247fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
4248    indent_size_for_text(text.chars_at(Point::new(row, 0)))
4249}
4250
4251fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
4252    let mut result = IndentSize::spaces(0);
4253    for c in text {
4254        let kind = match c {
4255            ' ' => IndentKind::Space,
4256            '\t' => IndentKind::Tab,
4257            _ => break,
4258        };
4259        if result.len == 0 {
4260            result.kind = kind;
4261        }
4262        result.len += 1;
4263    }
4264    result
4265}
4266
4267impl Clone for BufferSnapshot {
4268    fn clone(&self) -> Self {
4269        Self {
4270            text: self.text.clone(),
4271            syntax: self.syntax.clone(),
4272            file: self.file.clone(),
4273            remote_selections: self.remote_selections.clone(),
4274            diagnostics: self.diagnostics.clone(),
4275            language: self.language.clone(),
4276            non_text_state_update_count: self.non_text_state_update_count,
4277        }
4278    }
4279}
4280
4281impl Deref for BufferSnapshot {
4282    type Target = text::BufferSnapshot;
4283
4284    fn deref(&self) -> &Self::Target {
4285        &self.text
4286    }
4287}
4288
4289unsafe impl Send for BufferChunks<'_> {}
4290
4291impl<'a> BufferChunks<'a> {
4292    pub(crate) fn new(
4293        text: &'a Rope,
4294        range: Range<usize>,
4295        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
4296        diagnostics: bool,
4297        buffer_snapshot: Option<&'a BufferSnapshot>,
4298    ) -> Self {
4299        let mut highlights = None;
4300        if let Some((captures, highlight_maps)) = syntax {
4301            highlights = Some(BufferChunkHighlights {
4302                captures,
4303                next_capture: None,
4304                stack: Default::default(),
4305                highlight_maps,
4306            })
4307        }
4308
4309        let diagnostic_endpoints = diagnostics.then(|| Vec::new().into_iter().peekable());
4310        let chunks = text.chunks_in_range(range.clone());
4311
4312        let mut this = BufferChunks {
4313            range,
4314            buffer_snapshot,
4315            chunks,
4316            diagnostic_endpoints,
4317            error_depth: 0,
4318            warning_depth: 0,
4319            information_depth: 0,
4320            hint_depth: 0,
4321            unnecessary_depth: 0,
4322            highlights,
4323        };
4324        this.initialize_diagnostic_endpoints();
4325        this
4326    }
4327
4328    /// Seeks to the given byte offset in the buffer.
4329    pub fn seek(&mut self, range: Range<usize>) {
4330        let old_range = std::mem::replace(&mut self.range, range.clone());
4331        self.chunks.set_range(self.range.clone());
4332        if let Some(highlights) = self.highlights.as_mut() {
4333            if old_range.start <= self.range.start && old_range.end >= self.range.end {
4334                // Reuse existing highlights stack, as the new range is a subrange of the old one.
4335                highlights
4336                    .stack
4337                    .retain(|(end_offset, _)| *end_offset > range.start);
4338                if let Some(capture) = &highlights.next_capture {
4339                    if range.start >= capture.node.start_byte() {
4340                        let next_capture_end = capture.node.end_byte();
4341                        if range.start < next_capture_end {
4342                            highlights.stack.push((
4343                                next_capture_end,
4344                                highlights.highlight_maps[capture.grammar_index].get(capture.index),
4345                            ));
4346                        }
4347                        highlights.next_capture.take();
4348                    }
4349                }
4350            } else if let Some(snapshot) = self.buffer_snapshot {
4351                let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
4352                *highlights = BufferChunkHighlights {
4353                    captures,
4354                    next_capture: None,
4355                    stack: Default::default(),
4356                    highlight_maps,
4357                };
4358            } else {
4359                // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
4360                // Seeking such BufferChunks is not supported.
4361                debug_assert!(
4362                    false,
4363                    "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot"
4364                );
4365            }
4366
4367            highlights.captures.set_byte_range(self.range.clone());
4368            self.initialize_diagnostic_endpoints();
4369        }
4370    }
4371
4372    fn initialize_diagnostic_endpoints(&mut self) {
4373        if let Some(diagnostics) = self.diagnostic_endpoints.as_mut() {
4374            if let Some(buffer) = self.buffer_snapshot {
4375                let mut diagnostic_endpoints = Vec::new();
4376                for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
4377                    diagnostic_endpoints.push(DiagnosticEndpoint {
4378                        offset: entry.range.start,
4379                        is_start: true,
4380                        severity: entry.diagnostic.severity,
4381                        is_unnecessary: entry.diagnostic.is_unnecessary,
4382                    });
4383                    diagnostic_endpoints.push(DiagnosticEndpoint {
4384                        offset: entry.range.end,
4385                        is_start: false,
4386                        severity: entry.diagnostic.severity,
4387                        is_unnecessary: entry.diagnostic.is_unnecessary,
4388                    });
4389                }
4390                diagnostic_endpoints
4391                    .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
4392                *diagnostics = diagnostic_endpoints.into_iter().peekable();
4393                self.hint_depth = 0;
4394                self.error_depth = 0;
4395                self.warning_depth = 0;
4396                self.information_depth = 0;
4397            }
4398        }
4399    }
4400
4401    /// The current byte offset in the buffer.
4402    pub fn offset(&self) -> usize {
4403        self.range.start
4404    }
4405
4406    pub fn range(&self) -> Range<usize> {
4407        self.range.clone()
4408    }
4409
4410    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
4411        let depth = match endpoint.severity {
4412            DiagnosticSeverity::ERROR => &mut self.error_depth,
4413            DiagnosticSeverity::WARNING => &mut self.warning_depth,
4414            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
4415            DiagnosticSeverity::HINT => &mut self.hint_depth,
4416            _ => return,
4417        };
4418        if endpoint.is_start {
4419            *depth += 1;
4420        } else {
4421            *depth -= 1;
4422        }
4423
4424        if endpoint.is_unnecessary {
4425            if endpoint.is_start {
4426                self.unnecessary_depth += 1;
4427            } else {
4428                self.unnecessary_depth -= 1;
4429            }
4430        }
4431    }
4432
4433    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
4434        if self.error_depth > 0 {
4435            Some(DiagnosticSeverity::ERROR)
4436        } else if self.warning_depth > 0 {
4437            Some(DiagnosticSeverity::WARNING)
4438        } else if self.information_depth > 0 {
4439            Some(DiagnosticSeverity::INFORMATION)
4440        } else if self.hint_depth > 0 {
4441            Some(DiagnosticSeverity::HINT)
4442        } else {
4443            None
4444        }
4445    }
4446
4447    fn current_code_is_unnecessary(&self) -> bool {
4448        self.unnecessary_depth > 0
4449    }
4450}
4451
4452impl<'a> Iterator for BufferChunks<'a> {
4453    type Item = Chunk<'a>;
4454
4455    fn next(&mut self) -> Option<Self::Item> {
4456        let mut next_capture_start = usize::MAX;
4457        let mut next_diagnostic_endpoint = usize::MAX;
4458
4459        if let Some(highlights) = self.highlights.as_mut() {
4460            while let Some((parent_capture_end, _)) = highlights.stack.last() {
4461                if *parent_capture_end <= self.range.start {
4462                    highlights.stack.pop();
4463                } else {
4464                    break;
4465                }
4466            }
4467
4468            if highlights.next_capture.is_none() {
4469                highlights.next_capture = highlights.captures.next();
4470            }
4471
4472            while let Some(capture) = highlights.next_capture.as_ref() {
4473                if self.range.start < capture.node.start_byte() {
4474                    next_capture_start = capture.node.start_byte();
4475                    break;
4476                } else {
4477                    let highlight_id =
4478                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
4479                    highlights
4480                        .stack
4481                        .push((capture.node.end_byte(), highlight_id));
4482                    highlights.next_capture = highlights.captures.next();
4483                }
4484            }
4485        }
4486
4487        let mut diagnostic_endpoints = std::mem::take(&mut self.diagnostic_endpoints);
4488        if let Some(diagnostic_endpoints) = diagnostic_endpoints.as_mut() {
4489            while let Some(endpoint) = diagnostic_endpoints.peek().copied() {
4490                if endpoint.offset <= self.range.start {
4491                    self.update_diagnostic_depths(endpoint);
4492                    diagnostic_endpoints.next();
4493                } else {
4494                    next_diagnostic_endpoint = endpoint.offset;
4495                    break;
4496                }
4497            }
4498        }
4499        self.diagnostic_endpoints = diagnostic_endpoints;
4500
4501        if let Some(chunk) = self.chunks.peek() {
4502            let chunk_start = self.range.start;
4503            let mut chunk_end = (self.chunks.offset() + chunk.len())
4504                .min(next_capture_start)
4505                .min(next_diagnostic_endpoint);
4506            let mut highlight_id = None;
4507            if let Some(highlights) = self.highlights.as_ref() {
4508                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
4509                    chunk_end = chunk_end.min(*parent_capture_end);
4510                    highlight_id = Some(*parent_highlight_id);
4511                }
4512            }
4513
4514            let slice =
4515                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
4516            self.range.start = chunk_end;
4517            if self.range.start == self.chunks.offset() + chunk.len() {
4518                self.chunks.next().unwrap();
4519            }
4520
4521            Some(Chunk {
4522                text: slice,
4523                syntax_highlight_id: highlight_id,
4524                diagnostic_severity: self.current_diagnostic_severity(),
4525                is_unnecessary: self.current_code_is_unnecessary(),
4526                ..Default::default()
4527            })
4528        } else {
4529            None
4530        }
4531    }
4532}
4533
4534impl operation_queue::Operation for Operation {
4535    fn lamport_timestamp(&self) -> clock::Lamport {
4536        match self {
4537            Operation::Buffer(_) => {
4538                unreachable!("buffer operations should never be deferred at this layer")
4539            }
4540            Operation::UpdateDiagnostics {
4541                lamport_timestamp, ..
4542            }
4543            | Operation::UpdateSelections {
4544                lamport_timestamp, ..
4545            }
4546            | Operation::UpdateCompletionTriggers {
4547                lamport_timestamp, ..
4548            } => *lamport_timestamp,
4549        }
4550    }
4551}
4552
4553impl Default for Diagnostic {
4554    fn default() -> Self {
4555        Self {
4556            source: Default::default(),
4557            code: None,
4558            severity: DiagnosticSeverity::ERROR,
4559            message: Default::default(),
4560            group_id: 0,
4561            is_primary: false,
4562            is_disk_based: false,
4563            is_unnecessary: false,
4564            data: None,
4565        }
4566    }
4567}
4568
4569impl IndentSize {
4570    /// Returns an [`IndentSize`] representing the given spaces.
4571    pub fn spaces(len: u32) -> Self {
4572        Self {
4573            len,
4574            kind: IndentKind::Space,
4575        }
4576    }
4577
4578    /// Returns an [`IndentSize`] representing a tab.
4579    pub fn tab() -> Self {
4580        Self {
4581            len: 1,
4582            kind: IndentKind::Tab,
4583        }
4584    }
4585
4586    /// An iterator over the characters represented by this [`IndentSize`].
4587    pub fn chars(&self) -> impl Iterator<Item = char> {
4588        iter::repeat(self.char()).take(self.len as usize)
4589    }
4590
4591    /// The character representation of this [`IndentSize`].
4592    pub fn char(&self) -> char {
4593        match self.kind {
4594            IndentKind::Space => ' ',
4595            IndentKind::Tab => '\t',
4596        }
4597    }
4598
4599    /// Consumes the current [`IndentSize`] and returns a new one that has
4600    /// been shrunk or enlarged by the given size along the given direction.
4601    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4602        match direction {
4603            Ordering::Less => {
4604                if self.kind == size.kind && self.len >= size.len {
4605                    self.len -= size.len;
4606                }
4607            }
4608            Ordering::Equal => {}
4609            Ordering::Greater => {
4610                if self.len == 0 {
4611                    self = size;
4612                } else if self.kind == size.kind {
4613                    self.len += size.len;
4614                }
4615            }
4616        }
4617        self
4618    }
4619
4620    pub fn len_with_expanded_tabs(&self, tab_size: NonZeroU32) -> usize {
4621        match self.kind {
4622            IndentKind::Space => self.len as usize,
4623            IndentKind::Tab => self.len as usize * tab_size.get() as usize,
4624        }
4625    }
4626}
4627
4628#[cfg(any(test, feature = "test-support"))]
4629pub struct TestFile {
4630    pub path: Arc<Path>,
4631    pub root_name: String,
4632    pub local_root: Option<PathBuf>,
4633}
4634
4635#[cfg(any(test, feature = "test-support"))]
4636impl File for TestFile {
4637    fn path(&self) -> &Arc<Path> {
4638        &self.path
4639    }
4640
4641    fn full_path(&self, _: &gpui::App) -> PathBuf {
4642        PathBuf::from(&self.root_name).join(self.path.as_ref())
4643    }
4644
4645    fn as_local(&self) -> Option<&dyn LocalFile> {
4646        if self.local_root.is_some() {
4647            Some(self)
4648        } else {
4649            None
4650        }
4651    }
4652
4653    fn disk_state(&self) -> DiskState {
4654        unimplemented!()
4655    }
4656
4657    fn file_name<'a>(&'a self, _: &'a gpui::App) -> &'a std::ffi::OsStr {
4658        self.path().file_name().unwrap_or(self.root_name.as_ref())
4659    }
4660
4661    fn worktree_id(&self, _: &App) -> WorktreeId {
4662        WorktreeId::from_usize(0)
4663    }
4664
4665    fn as_any(&self) -> &dyn std::any::Any {
4666        unimplemented!()
4667    }
4668
4669    fn to_proto(&self, _: &App) -> rpc::proto::File {
4670        unimplemented!()
4671    }
4672
4673    fn is_private(&self) -> bool {
4674        false
4675    }
4676}
4677
4678#[cfg(any(test, feature = "test-support"))]
4679impl LocalFile for TestFile {
4680    fn abs_path(&self, _cx: &App) -> PathBuf {
4681        PathBuf::from(self.local_root.as_ref().unwrap())
4682            .join(&self.root_name)
4683            .join(self.path.as_ref())
4684    }
4685
4686    fn load(&self, _cx: &App) -> Task<Result<String>> {
4687        unimplemented!()
4688    }
4689
4690    fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
4691        unimplemented!()
4692    }
4693}
4694
4695pub(crate) fn contiguous_ranges(
4696    values: impl Iterator<Item = u32>,
4697    max_len: usize,
4698) -> impl Iterator<Item = Range<u32>> {
4699    let mut values = values;
4700    let mut current_range: Option<Range<u32>> = None;
4701    std::iter::from_fn(move || {
4702        loop {
4703            if let Some(value) = values.next() {
4704                if let Some(range) = &mut current_range {
4705                    if value == range.end && range.len() < max_len {
4706                        range.end += 1;
4707                        continue;
4708                    }
4709                }
4710
4711                let prev_range = current_range.clone();
4712                current_range = Some(value..(value + 1));
4713                if prev_range.is_some() {
4714                    return prev_range;
4715                }
4716            } else {
4717                return current_range.take();
4718            }
4719        }
4720    })
4721}
4722
4723#[derive(Default, Debug)]
4724pub struct CharClassifier {
4725    scope: Option<LanguageScope>,
4726    for_completion: bool,
4727    ignore_punctuation: bool,
4728}
4729
4730impl CharClassifier {
4731    pub fn new(scope: Option<LanguageScope>) -> Self {
4732        Self {
4733            scope,
4734            for_completion: false,
4735            ignore_punctuation: false,
4736        }
4737    }
4738
4739    pub fn for_completion(self, for_completion: bool) -> Self {
4740        Self {
4741            for_completion,
4742            ..self
4743        }
4744    }
4745
4746    pub fn ignore_punctuation(self, ignore_punctuation: bool) -> Self {
4747        Self {
4748            ignore_punctuation,
4749            ..self
4750        }
4751    }
4752
4753    pub fn is_whitespace(&self, c: char) -> bool {
4754        self.kind(c) == CharKind::Whitespace
4755    }
4756
4757    pub fn is_word(&self, c: char) -> bool {
4758        self.kind(c) == CharKind::Word
4759    }
4760
4761    pub fn is_punctuation(&self, c: char) -> bool {
4762        self.kind(c) == CharKind::Punctuation
4763    }
4764
4765    pub fn kind_with(&self, c: char, ignore_punctuation: bool) -> CharKind {
4766        if c.is_alphanumeric() || c == '_' {
4767            return CharKind::Word;
4768        }
4769
4770        if let Some(scope) = &self.scope {
4771            let characters = if self.for_completion {
4772                scope.completion_query_characters()
4773            } else {
4774                scope.word_characters()
4775            };
4776            if let Some(characters) = characters {
4777                if characters.contains(&c) {
4778                    return CharKind::Word;
4779                }
4780            }
4781        }
4782
4783        if c.is_whitespace() {
4784            return CharKind::Whitespace;
4785        }
4786
4787        if ignore_punctuation {
4788            CharKind::Word
4789        } else {
4790            CharKind::Punctuation
4791        }
4792    }
4793
4794    pub fn kind(&self, c: char) -> CharKind {
4795        self.kind_with(c, self.ignore_punctuation)
4796    }
4797}
4798
4799/// Find all of the ranges of whitespace that occur at the ends of lines
4800/// in the given rope.
4801///
4802/// This could also be done with a regex search, but this implementation
4803/// avoids copying text.
4804pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4805    let mut ranges = Vec::new();
4806
4807    let mut offset = 0;
4808    let mut prev_chunk_trailing_whitespace_range = 0..0;
4809    for chunk in rope.chunks() {
4810        let mut prev_line_trailing_whitespace_range = 0..0;
4811        for (i, line) in chunk.split('\n').enumerate() {
4812            let line_end_offset = offset + line.len();
4813            let trimmed_line_len = line.trim_end_matches([' ', '\t']).len();
4814            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4815
4816            if i == 0 && trimmed_line_len == 0 {
4817                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4818            }
4819            if !prev_line_trailing_whitespace_range.is_empty() {
4820                ranges.push(prev_line_trailing_whitespace_range);
4821            }
4822
4823            offset = line_end_offset + 1;
4824            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4825        }
4826
4827        offset -= 1;
4828        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4829    }
4830
4831    if !prev_chunk_trailing_whitespace_range.is_empty() {
4832        ranges.push(prev_chunk_trailing_whitespace_range);
4833    }
4834
4835    ranges
4836}