buffer.rs

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