buffer.rs

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