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