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