buffer.rs

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