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