buffer.rs

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