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