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 || self.has_unsaved_edits() {
1954            return true;
1955        }
1956        match self.file.as_ref().map(|f| f.disk_state()) {
1957            Some(DiskState::New) => !self.is_empty(),
1958            Some(DiskState::Deleted) => true,
1959            _ => false,
1960        }
1961    }
1962
1963    /// Checks if the buffer and its file have both changed since the buffer
1964    /// was last saved or reloaded.
1965    pub fn has_conflict(&self) -> bool {
1966        if self.has_conflict {
1967            return true;
1968        }
1969        let Some(file) = self.file.as_ref() else {
1970            return false;
1971        };
1972        match file.disk_state() {
1973            DiskState::New => false,
1974            DiskState::Present { mtime } => match self.saved_mtime {
1975                Some(saved_mtime) => {
1976                    mtime.bad_is_greater_than(saved_mtime) && self.has_unsaved_edits()
1977                }
1978                None => true,
1979            },
1980            DiskState::Deleted => true,
1981        }
1982    }
1983
1984    /// Gets a [`Subscription`] that tracks all of the changes to the buffer's text.
1985    pub fn subscribe(&mut self) -> Subscription {
1986        self.text.subscribe()
1987    }
1988
1989    /// Adds a bit to the list of bits that are set when the buffer's text changes.
1990    ///
1991    /// This allows downstream code to check if the buffer's text has changed without
1992    /// waiting for an effect cycle, which would be required if using eents.
1993    pub fn record_changes(&mut self, bit: rc::Weak<Cell<bool>>) {
1994        if let Err(ix) = self
1995            .change_bits
1996            .binary_search_by_key(&rc::Weak::as_ptr(&bit), rc::Weak::as_ptr)
1997        {
1998            self.change_bits.insert(ix, bit);
1999        }
2000    }
2001
2002    fn was_changed(&mut self) {
2003        self.change_bits.retain(|change_bit| {
2004            change_bit.upgrade().map_or(false, |bit| {
2005                bit.replace(true);
2006                true
2007            })
2008        });
2009    }
2010
2011    /// Starts a transaction, if one is not already in-progress. When undoing or
2012    /// redoing edits, all of the edits performed within a transaction are undone
2013    /// or redone together.
2014    pub fn start_transaction(&mut self) -> Option<TransactionId> {
2015        self.start_transaction_at(Instant::now())
2016    }
2017
2018    /// Starts a transaction, providing the current time. Subsequent transactions
2019    /// that occur within a short period of time will be grouped together. This
2020    /// is controlled by the buffer's undo grouping duration.
2021    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
2022        self.transaction_depth += 1;
2023        if self.was_dirty_before_starting_transaction.is_none() {
2024            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
2025        }
2026        self.text.start_transaction_at(now)
2027    }
2028
2029    /// Terminates the current transaction, if this is the outermost transaction.
2030    pub fn end_transaction(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2031        self.end_transaction_at(Instant::now(), cx)
2032    }
2033
2034    /// Terminates the current transaction, providing the current time. Subsequent transactions
2035    /// that occur within a short period of time will be grouped together. This
2036    /// is controlled by the buffer's undo grouping duration.
2037    pub fn end_transaction_at(
2038        &mut self,
2039        now: Instant,
2040        cx: &mut Context<Self>,
2041    ) -> Option<TransactionId> {
2042        assert!(self.transaction_depth > 0);
2043        self.transaction_depth -= 1;
2044        let was_dirty = if self.transaction_depth == 0 {
2045            self.was_dirty_before_starting_transaction.take().unwrap()
2046        } else {
2047            false
2048        };
2049        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
2050            self.did_edit(&start_version, was_dirty, cx);
2051            Some(transaction_id)
2052        } else {
2053            None
2054        }
2055    }
2056
2057    /// Manually add a transaction to the buffer's undo history.
2058    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
2059        self.text.push_transaction(transaction, now);
2060    }
2061
2062    /// Prevent the last transaction from being grouped with any subsequent transactions,
2063    /// even if they occur with the buffer's undo grouping duration.
2064    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
2065        self.text.finalize_last_transaction()
2066    }
2067
2068    /// Manually group all changes since a given transaction.
2069    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
2070        self.text.group_until_transaction(transaction_id);
2071    }
2072
2073    /// Manually remove a transaction from the buffer's undo history
2074    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
2075        self.text.forget_transaction(transaction_id);
2076    }
2077
2078    /// Manually merge two adjacent transactions in the buffer's undo history.
2079    pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
2080        self.text.merge_transactions(transaction, destination);
2081    }
2082
2083    /// Waits for the buffer to receive operations with the given timestamps.
2084    pub fn wait_for_edits(
2085        &mut self,
2086        edit_ids: impl IntoIterator<Item = clock::Lamport>,
2087    ) -> impl Future<Output = Result<()>> {
2088        self.text.wait_for_edits(edit_ids)
2089    }
2090
2091    /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
2092    pub fn wait_for_anchors(
2093        &mut self,
2094        anchors: impl IntoIterator<Item = Anchor>,
2095    ) -> impl 'static + Future<Output = Result<()>> {
2096        self.text.wait_for_anchors(anchors)
2097    }
2098
2099    /// Waits for the buffer to receive operations up to the given version.
2100    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
2101        self.text.wait_for_version(version)
2102    }
2103
2104    /// Forces all futures returned by [`Buffer::wait_for_version`], [`Buffer::wait_for_edits`], or
2105    /// [`Buffer::wait_for_version`] to resolve with an error.
2106    pub fn give_up_waiting(&mut self) {
2107        self.text.give_up_waiting();
2108    }
2109
2110    /// Stores a set of selections that should be broadcasted to all of the buffer's replicas.
2111    pub fn set_active_selections(
2112        &mut self,
2113        selections: Arc<[Selection<Anchor>]>,
2114        line_mode: bool,
2115        cursor_shape: CursorShape,
2116        cx: &mut Context<Self>,
2117    ) {
2118        let lamport_timestamp = self.text.lamport_clock.tick();
2119        self.remote_selections.insert(
2120            self.text.replica_id(),
2121            SelectionSet {
2122                selections: selections.clone(),
2123                lamport_timestamp,
2124                line_mode,
2125                cursor_shape,
2126            },
2127        );
2128        self.send_operation(
2129            Operation::UpdateSelections {
2130                selections,
2131                line_mode,
2132                lamport_timestamp,
2133                cursor_shape,
2134            },
2135            true,
2136            cx,
2137        );
2138        self.non_text_state_update_count += 1;
2139        cx.notify();
2140    }
2141
2142    /// Clears the selections, so that other replicas of the buffer do not see any selections for
2143    /// this replica.
2144    pub fn remove_active_selections(&mut self, cx: &mut Context<Self>) {
2145        if self
2146            .remote_selections
2147            .get(&self.text.replica_id())
2148            .map_or(true, |set| !set.selections.is_empty())
2149        {
2150            self.set_active_selections(Arc::default(), false, Default::default(), cx);
2151        }
2152    }
2153
2154    /// Replaces the buffer's entire text.
2155    pub fn set_text<T>(&mut self, text: T, cx: &mut Context<Self>) -> Option<clock::Lamport>
2156    where
2157        T: Into<Arc<str>>,
2158    {
2159        self.autoindent_requests.clear();
2160        self.edit([(0..self.len(), text)], None, cx)
2161    }
2162
2163    /// Applies the given edits to the buffer. Each edit is specified as a range of text to
2164    /// delete, and a string of text to insert at that location.
2165    ///
2166    /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
2167    /// request for the edited ranges, which will be processed when the buffer finishes
2168    /// parsing.
2169    ///
2170    /// Parsing takes place at the end of a transaction, and may compute synchronously
2171    /// or asynchronously, depending on the changes.
2172    pub fn edit<I, S, T>(
2173        &mut self,
2174        edits_iter: I,
2175        autoindent_mode: Option<AutoindentMode>,
2176        cx: &mut Context<Self>,
2177    ) -> Option<clock::Lamport>
2178    where
2179        I: IntoIterator<Item = (Range<S>, T)>,
2180        S: ToOffset,
2181        T: Into<Arc<str>>,
2182    {
2183        // Skip invalid edits and coalesce contiguous ones.
2184        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
2185
2186        for (range, new_text) in edits_iter {
2187            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2188
2189            if range.start > range.end {
2190                mem::swap(&mut range.start, &mut range.end);
2191            }
2192            let new_text = new_text.into();
2193            if !new_text.is_empty() || !range.is_empty() {
2194                if let Some((prev_range, prev_text)) = edits.last_mut() {
2195                    if prev_range.end >= range.start {
2196                        prev_range.end = cmp::max(prev_range.end, range.end);
2197                        *prev_text = format!("{prev_text}{new_text}").into();
2198                    } else {
2199                        edits.push((range, new_text));
2200                    }
2201                } else {
2202                    edits.push((range, new_text));
2203                }
2204            }
2205        }
2206        if edits.is_empty() {
2207            return None;
2208        }
2209
2210        self.start_transaction();
2211        self.pending_autoindent.take();
2212        let autoindent_request = autoindent_mode
2213            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
2214
2215        let edit_operation = self.text.edit(edits.iter().cloned());
2216        let edit_id = edit_operation.timestamp();
2217
2218        if let Some((before_edit, mode)) = autoindent_request {
2219            let mut delta = 0isize;
2220            let entries = edits
2221                .into_iter()
2222                .enumerate()
2223                .zip(&edit_operation.as_edit().unwrap().new_text)
2224                .map(|((ix, (range, _)), new_text)| {
2225                    let new_text_length = new_text.len();
2226                    let old_start = range.start.to_point(&before_edit);
2227                    let new_start = (delta + range.start as isize) as usize;
2228                    let range_len = range.end - range.start;
2229                    delta += new_text_length as isize - range_len as isize;
2230
2231                    // Decide what range of the insertion to auto-indent, and whether
2232                    // the first line of the insertion should be considered a newly-inserted line
2233                    // or an edit to an existing line.
2234                    let mut range_of_insertion_to_indent = 0..new_text_length;
2235                    let mut first_line_is_new = true;
2236
2237                    let old_line_start = before_edit.indent_size_for_line(old_start.row).len;
2238                    let old_line_end = before_edit.line_len(old_start.row);
2239
2240                    if old_start.column > old_line_start {
2241                        first_line_is_new = false;
2242                    }
2243
2244                    if !new_text.contains('\n')
2245                        && (old_start.column + (range_len as u32) < old_line_end
2246                            || old_line_end == old_line_start)
2247                    {
2248                        first_line_is_new = false;
2249                    }
2250
2251                    // When inserting text starting with a newline, avoid auto-indenting the
2252                    // previous line.
2253                    if new_text.starts_with('\n') {
2254                        range_of_insertion_to_indent.start += 1;
2255                        first_line_is_new = true;
2256                    }
2257
2258                    let mut original_indent_column = None;
2259                    if let AutoindentMode::Block {
2260                        original_indent_columns,
2261                    } = &mode
2262                    {
2263                        original_indent_column = Some(
2264                            original_indent_columns
2265                                .get(ix)
2266                                .copied()
2267                                .flatten()
2268                                .unwrap_or_else(|| {
2269                                    indent_size_for_text(
2270                                        new_text[range_of_insertion_to_indent.clone()].chars(),
2271                                    )
2272                                    .len
2273                                }),
2274                        );
2275
2276                        // Avoid auto-indenting the line after the edit.
2277                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
2278                            range_of_insertion_to_indent.end -= 1;
2279                        }
2280                    }
2281
2282                    AutoindentRequestEntry {
2283                        first_line_is_new,
2284                        original_indent_column,
2285                        indent_size: before_edit.language_indent_size_at(range.start, cx),
2286                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
2287                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
2288                    }
2289                })
2290                .collect();
2291
2292            self.autoindent_requests.push(Arc::new(AutoindentRequest {
2293                before_edit,
2294                entries,
2295                is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
2296                ignore_empty_lines: false,
2297            }));
2298        }
2299
2300        self.end_transaction(cx);
2301        self.send_operation(Operation::Buffer(edit_operation), true, cx);
2302        Some(edit_id)
2303    }
2304
2305    fn did_edit(&mut self, old_version: &clock::Global, was_dirty: bool, cx: &mut Context<Self>) {
2306        self.was_changed();
2307
2308        if self.edits_since::<usize>(old_version).next().is_none() {
2309            return;
2310        }
2311
2312        self.reparse(cx);
2313        cx.emit(BufferEvent::Edited);
2314        if was_dirty != self.is_dirty() {
2315            cx.emit(BufferEvent::DirtyChanged);
2316        }
2317        cx.notify();
2318    }
2319
2320    pub fn autoindent_ranges<I, T>(&mut self, ranges: I, cx: &mut Context<Self>)
2321    where
2322        I: IntoIterator<Item = Range<T>>,
2323        T: ToOffset + Copy,
2324    {
2325        let before_edit = self.snapshot();
2326        let entries = ranges
2327            .into_iter()
2328            .map(|range| AutoindentRequestEntry {
2329                range: before_edit.anchor_before(range.start)..before_edit.anchor_after(range.end),
2330                first_line_is_new: true,
2331                indent_size: before_edit.language_indent_size_at(range.start, cx),
2332                original_indent_column: None,
2333            })
2334            .collect();
2335        self.autoindent_requests.push(Arc::new(AutoindentRequest {
2336            before_edit,
2337            entries,
2338            is_block_mode: false,
2339            ignore_empty_lines: true,
2340        }));
2341        self.request_autoindent(cx);
2342    }
2343
2344    // Inserts newlines at the given position to create an empty line, returning the start of the new line.
2345    // You can also request the insertion of empty lines above and below the line starting at the returned point.
2346    pub fn insert_empty_line(
2347        &mut self,
2348        position: impl ToPoint,
2349        space_above: bool,
2350        space_below: bool,
2351        cx: &mut Context<Self>,
2352    ) -> Point {
2353        let mut position = position.to_point(self);
2354
2355        self.start_transaction();
2356
2357        self.edit(
2358            [(position..position, "\n")],
2359            Some(AutoindentMode::EachLine),
2360            cx,
2361        );
2362
2363        if position.column > 0 {
2364            position += Point::new(1, 0);
2365        }
2366
2367        if !self.is_line_blank(position.row) {
2368            self.edit(
2369                [(position..position, "\n")],
2370                Some(AutoindentMode::EachLine),
2371                cx,
2372            );
2373        }
2374
2375        if space_above && position.row > 0 && !self.is_line_blank(position.row - 1) {
2376            self.edit(
2377                [(position..position, "\n")],
2378                Some(AutoindentMode::EachLine),
2379                cx,
2380            );
2381            position.row += 1;
2382        }
2383
2384        if space_below
2385            && (position.row == self.max_point().row || !self.is_line_blank(position.row + 1))
2386        {
2387            self.edit(
2388                [(position..position, "\n")],
2389                Some(AutoindentMode::EachLine),
2390                cx,
2391            );
2392        }
2393
2394        self.end_transaction(cx);
2395
2396        position
2397    }
2398
2399    /// Applies the given remote operations to the buffer.
2400    pub fn apply_ops<I: IntoIterator<Item = Operation>>(&mut self, ops: I, cx: &mut Context<Self>) {
2401        self.pending_autoindent.take();
2402        let was_dirty = self.is_dirty();
2403        let old_version = self.version.clone();
2404        let mut deferred_ops = Vec::new();
2405        let buffer_ops = ops
2406            .into_iter()
2407            .filter_map(|op| match op {
2408                Operation::Buffer(op) => Some(op),
2409                _ => {
2410                    if self.can_apply_op(&op) {
2411                        self.apply_op(op, cx);
2412                    } else {
2413                        deferred_ops.push(op);
2414                    }
2415                    None
2416                }
2417            })
2418            .collect::<Vec<_>>();
2419        for operation in buffer_ops.iter() {
2420            self.send_operation(Operation::Buffer(operation.clone()), false, cx);
2421        }
2422        self.text.apply_ops(buffer_ops);
2423        self.deferred_ops.insert(deferred_ops);
2424        self.flush_deferred_ops(cx);
2425        self.did_edit(&old_version, was_dirty, cx);
2426        // Notify independently of whether the buffer was edited as the operations could include a
2427        // selection update.
2428        cx.notify();
2429    }
2430
2431    fn flush_deferred_ops(&mut self, cx: &mut Context<Self>) {
2432        let mut deferred_ops = Vec::new();
2433        for op in self.deferred_ops.drain().iter().cloned() {
2434            if self.can_apply_op(&op) {
2435                self.apply_op(op, cx);
2436            } else {
2437                deferred_ops.push(op);
2438            }
2439        }
2440        self.deferred_ops.insert(deferred_ops);
2441    }
2442
2443    pub fn has_deferred_ops(&self) -> bool {
2444        !self.deferred_ops.is_empty() || self.text.has_deferred_ops()
2445    }
2446
2447    fn can_apply_op(&self, operation: &Operation) -> bool {
2448        match operation {
2449            Operation::Buffer(_) => {
2450                unreachable!("buffer operations should never be applied at this layer")
2451            }
2452            Operation::UpdateDiagnostics {
2453                diagnostics: diagnostic_set,
2454                ..
2455            } => diagnostic_set.iter().all(|diagnostic| {
2456                self.text.can_resolve(&diagnostic.range.start)
2457                    && self.text.can_resolve(&diagnostic.range.end)
2458            }),
2459            Operation::UpdateSelections { selections, .. } => selections
2460                .iter()
2461                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
2462            Operation::UpdateCompletionTriggers { .. } => true,
2463        }
2464    }
2465
2466    fn apply_op(&mut self, operation: Operation, cx: &mut Context<Self>) {
2467        match operation {
2468            Operation::Buffer(_) => {
2469                unreachable!("buffer operations should never be applied at this layer")
2470            }
2471            Operation::UpdateDiagnostics {
2472                server_id,
2473                diagnostics: diagnostic_set,
2474                lamport_timestamp,
2475            } => {
2476                let snapshot = self.snapshot();
2477                self.apply_diagnostic_update(
2478                    server_id,
2479                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
2480                    lamport_timestamp,
2481                    cx,
2482                );
2483            }
2484            Operation::UpdateSelections {
2485                selections,
2486                lamport_timestamp,
2487                line_mode,
2488                cursor_shape,
2489            } => {
2490                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
2491                    if set.lamport_timestamp > lamport_timestamp {
2492                        return;
2493                    }
2494                }
2495
2496                self.remote_selections.insert(
2497                    lamport_timestamp.replica_id,
2498                    SelectionSet {
2499                        selections,
2500                        lamport_timestamp,
2501                        line_mode,
2502                        cursor_shape,
2503                    },
2504                );
2505                self.text.lamport_clock.observe(lamport_timestamp);
2506                self.non_text_state_update_count += 1;
2507            }
2508            Operation::UpdateCompletionTriggers {
2509                triggers,
2510                lamport_timestamp,
2511                server_id,
2512            } => {
2513                if triggers.is_empty() {
2514                    self.completion_triggers_per_language_server
2515                        .remove(&server_id);
2516                    self.completion_triggers = self
2517                        .completion_triggers_per_language_server
2518                        .values()
2519                        .flat_map(|triggers| triggers.into_iter().cloned())
2520                        .collect();
2521                } else {
2522                    self.completion_triggers_per_language_server
2523                        .insert(server_id, triggers.iter().cloned().collect());
2524                    self.completion_triggers.extend(triggers);
2525                }
2526                self.text.lamport_clock.observe(lamport_timestamp);
2527            }
2528        }
2529    }
2530
2531    fn apply_diagnostic_update(
2532        &mut self,
2533        server_id: LanguageServerId,
2534        diagnostics: DiagnosticSet,
2535        lamport_timestamp: clock::Lamport,
2536        cx: &mut Context<Self>,
2537    ) {
2538        if lamport_timestamp > self.diagnostics_timestamp {
2539            let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
2540            if diagnostics.is_empty() {
2541                if let Ok(ix) = ix {
2542                    self.diagnostics.remove(ix);
2543                }
2544            } else {
2545                match ix {
2546                    Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
2547                    Ok(ix) => self.diagnostics[ix].1 = diagnostics,
2548                };
2549            }
2550            self.diagnostics_timestamp = lamport_timestamp;
2551            self.non_text_state_update_count += 1;
2552            self.text.lamport_clock.observe(lamport_timestamp);
2553            cx.notify();
2554            cx.emit(BufferEvent::DiagnosticsUpdated);
2555        }
2556    }
2557
2558    fn send_operation(&mut self, operation: Operation, is_local: bool, cx: &mut Context<Self>) {
2559        self.was_changed();
2560        cx.emit(BufferEvent::Operation {
2561            operation,
2562            is_local,
2563        });
2564    }
2565
2566    /// Removes the selections for a given peer.
2567    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut Context<Self>) {
2568        self.remote_selections.remove(&replica_id);
2569        cx.notify();
2570    }
2571
2572    /// Undoes the most recent transaction.
2573    pub fn undo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2574        let was_dirty = self.is_dirty();
2575        let old_version = self.version.clone();
2576
2577        if let Some((transaction_id, operation)) = self.text.undo() {
2578            self.send_operation(Operation::Buffer(operation), true, cx);
2579            self.did_edit(&old_version, was_dirty, cx);
2580            Some(transaction_id)
2581        } else {
2582            None
2583        }
2584    }
2585
2586    /// Manually undoes a specific transaction in the buffer's undo history.
2587    pub fn undo_transaction(
2588        &mut self,
2589        transaction_id: TransactionId,
2590        cx: &mut Context<Self>,
2591    ) -> bool {
2592        let was_dirty = self.is_dirty();
2593        let old_version = self.version.clone();
2594        if let Some(operation) = self.text.undo_transaction(transaction_id) {
2595            self.send_operation(Operation::Buffer(operation), true, cx);
2596            self.did_edit(&old_version, was_dirty, cx);
2597            true
2598        } else {
2599            false
2600        }
2601    }
2602
2603    /// Manually undoes all changes after a given transaction in the buffer's undo history.
2604    pub fn undo_to_transaction(
2605        &mut self,
2606        transaction_id: TransactionId,
2607        cx: &mut Context<Self>,
2608    ) -> bool {
2609        let was_dirty = self.is_dirty();
2610        let old_version = self.version.clone();
2611
2612        let operations = self.text.undo_to_transaction(transaction_id);
2613        let undone = !operations.is_empty();
2614        for operation in operations {
2615            self.send_operation(Operation::Buffer(operation), true, cx);
2616        }
2617        if undone {
2618            self.did_edit(&old_version, was_dirty, cx)
2619        }
2620        undone
2621    }
2622
2623    pub fn undo_operations(&mut self, counts: HashMap<Lamport, u32>, cx: &mut Context<Buffer>) {
2624        let was_dirty = self.is_dirty();
2625        let operation = self.text.undo_operations(counts);
2626        let old_version = self.version.clone();
2627        self.send_operation(Operation::Buffer(operation), true, cx);
2628        self.did_edit(&old_version, was_dirty, cx);
2629    }
2630
2631    /// Manually redoes a specific transaction in the buffer's redo history.
2632    pub fn redo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
2633        let was_dirty = self.is_dirty();
2634        let old_version = self.version.clone();
2635
2636        if let Some((transaction_id, operation)) = self.text.redo() {
2637            self.send_operation(Operation::Buffer(operation), true, cx);
2638            self.did_edit(&old_version, was_dirty, cx);
2639            Some(transaction_id)
2640        } else {
2641            None
2642        }
2643    }
2644
2645    /// Manually undoes all changes until a given transaction in the buffer's redo history.
2646    pub fn redo_to_transaction(
2647        &mut self,
2648        transaction_id: TransactionId,
2649        cx: &mut Context<Self>,
2650    ) -> bool {
2651        let was_dirty = self.is_dirty();
2652        let old_version = self.version.clone();
2653
2654        let operations = self.text.redo_to_transaction(transaction_id);
2655        let redone = !operations.is_empty();
2656        for operation in operations {
2657            self.send_operation(Operation::Buffer(operation), true, cx);
2658        }
2659        if redone {
2660            self.did_edit(&old_version, was_dirty, cx)
2661        }
2662        redone
2663    }
2664
2665    /// Override current completion triggers with the user-provided completion triggers.
2666    pub fn set_completion_triggers(
2667        &mut self,
2668        server_id: LanguageServerId,
2669        triggers: BTreeSet<String>,
2670        cx: &mut Context<Self>,
2671    ) {
2672        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2673        if triggers.is_empty() {
2674            self.completion_triggers_per_language_server
2675                .remove(&server_id);
2676            self.completion_triggers = self
2677                .completion_triggers_per_language_server
2678                .values()
2679                .flat_map(|triggers| triggers.into_iter().cloned())
2680                .collect();
2681        } else {
2682            self.completion_triggers_per_language_server
2683                .insert(server_id, triggers.clone());
2684            self.completion_triggers.extend(triggers.iter().cloned());
2685        }
2686        self.send_operation(
2687            Operation::UpdateCompletionTriggers {
2688                triggers: triggers.iter().cloned().collect(),
2689                lamport_timestamp: self.completion_triggers_timestamp,
2690                server_id,
2691            },
2692            true,
2693            cx,
2694        );
2695        cx.notify();
2696    }
2697
2698    /// Returns a list of strings which trigger a completion menu for this language.
2699    /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2700    pub fn completion_triggers(&self) -> &BTreeSet<String> {
2701        &self.completion_triggers
2702    }
2703
2704    /// Call this directly after performing edits to prevent the preview tab
2705    /// from being dismissed by those edits. It causes `should_dismiss_preview`
2706    /// to return false until there are additional edits.
2707    pub fn refresh_preview(&mut self) {
2708        self.preview_version = self.version.clone();
2709    }
2710
2711    /// Whether we should preserve the preview status of a tab containing this buffer.
2712    pub fn preserve_preview(&self) -> bool {
2713        !self.has_edits_since(&self.preview_version)
2714    }
2715}
2716
2717#[doc(hidden)]
2718#[cfg(any(test, feature = "test-support"))]
2719impl Buffer {
2720    pub fn edit_via_marked_text(
2721        &mut self,
2722        marked_string: &str,
2723        autoindent_mode: Option<AutoindentMode>,
2724        cx: &mut Context<Self>,
2725    ) {
2726        let edits = self.edits_for_marked_text(marked_string);
2727        self.edit(edits, autoindent_mode, cx);
2728    }
2729
2730    pub fn set_group_interval(&mut self, group_interval: Duration) {
2731        self.text.set_group_interval(group_interval);
2732    }
2733
2734    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize, cx: &mut Context<Self>)
2735    where
2736        T: rand::Rng,
2737    {
2738        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2739        let mut last_end = None;
2740        for _ in 0..old_range_count {
2741            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2742                break;
2743            }
2744
2745            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2746            let mut range = self.random_byte_range(new_start, rng);
2747            if rng.gen_bool(0.2) {
2748                mem::swap(&mut range.start, &mut range.end);
2749            }
2750            last_end = Some(range.end);
2751
2752            let new_text_len = rng.gen_range(0..10);
2753            let mut new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2754            new_text = new_text.to_uppercase();
2755
2756            edits.push((range, new_text));
2757        }
2758        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2759        self.edit(edits, None, cx);
2760    }
2761
2762    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut Context<Self>) {
2763        let was_dirty = self.is_dirty();
2764        let old_version = self.version.clone();
2765
2766        let ops = self.text.randomly_undo_redo(rng);
2767        if !ops.is_empty() {
2768            for op in ops {
2769                self.send_operation(Operation::Buffer(op), true, cx);
2770                self.did_edit(&old_version, was_dirty, cx);
2771            }
2772        }
2773    }
2774}
2775
2776impl EventEmitter<BufferEvent> for Buffer {}
2777
2778impl Deref for Buffer {
2779    type Target = TextBuffer;
2780
2781    fn deref(&self) -> &Self::Target {
2782        &self.text
2783    }
2784}
2785
2786impl BufferSnapshot {
2787    /// Returns [`IndentSize`] for a given line that respects user settings and
2788    /// language preferences.
2789    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2790        indent_size_for_line(self, row)
2791    }
2792
2793    /// Returns [`IndentSize`] for a given position that respects user settings
2794    /// and language preferences.
2795    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &App) -> IndentSize {
2796        let settings = language_settings(
2797            self.language_at(position).map(|l| l.name()),
2798            self.file(),
2799            cx,
2800        );
2801        if settings.hard_tabs {
2802            IndentSize::tab()
2803        } else {
2804            IndentSize::spaces(settings.tab_size.get())
2805        }
2806    }
2807
2808    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2809    /// is passed in as `single_indent_size`.
2810    pub fn suggested_indents(
2811        &self,
2812        rows: impl Iterator<Item = u32>,
2813        single_indent_size: IndentSize,
2814    ) -> BTreeMap<u32, IndentSize> {
2815        let mut result = BTreeMap::new();
2816
2817        for row_range in contiguous_ranges(rows, 10) {
2818            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2819                Some(suggestions) => suggestions,
2820                _ => break,
2821            };
2822
2823            for (row, suggestion) in row_range.zip(suggestions) {
2824                let indent_size = if let Some(suggestion) = suggestion {
2825                    result
2826                        .get(&suggestion.basis_row)
2827                        .copied()
2828                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2829                        .with_delta(suggestion.delta, single_indent_size)
2830                } else {
2831                    self.indent_size_for_line(row)
2832                };
2833
2834                result.insert(row, indent_size);
2835            }
2836        }
2837
2838        result
2839    }
2840
2841    fn suggest_autoindents(
2842        &self,
2843        row_range: Range<u32>,
2844    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2845        let config = &self.language.as_ref()?.config;
2846        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2847
2848        // Find the suggested indentation ranges based on the syntax tree.
2849        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2850        let end = Point::new(row_range.end, 0);
2851        let range = (start..end).to_offset(&self.text);
2852        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2853            Some(&grammar.indents_config.as_ref()?.query)
2854        });
2855        let indent_configs = matches
2856            .grammars()
2857            .iter()
2858            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2859            .collect::<Vec<_>>();
2860
2861        let mut indent_ranges = Vec::<Range<Point>>::new();
2862        let mut outdent_positions = Vec::<Point>::new();
2863        while let Some(mat) = matches.peek() {
2864            let mut start: Option<Point> = None;
2865            let mut end: Option<Point> = None;
2866
2867            let config = &indent_configs[mat.grammar_index];
2868            for capture in mat.captures {
2869                if capture.index == config.indent_capture_ix {
2870                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2871                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2872                } else if Some(capture.index) == config.start_capture_ix {
2873                    start = Some(Point::from_ts_point(capture.node.end_position()));
2874                } else if Some(capture.index) == config.end_capture_ix {
2875                    end = Some(Point::from_ts_point(capture.node.start_position()));
2876                } else if Some(capture.index) == config.outdent_capture_ix {
2877                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2878                }
2879            }
2880
2881            matches.advance();
2882            if let Some((start, end)) = start.zip(end) {
2883                if start.row == end.row {
2884                    continue;
2885                }
2886
2887                let range = start..end;
2888                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2889                    Err(ix) => indent_ranges.insert(ix, range),
2890                    Ok(ix) => {
2891                        let prev_range = &mut indent_ranges[ix];
2892                        prev_range.end = prev_range.end.max(range.end);
2893                    }
2894                }
2895            }
2896        }
2897
2898        let mut error_ranges = Vec::<Range<Point>>::new();
2899        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2900            grammar.error_query.as_ref()
2901        });
2902        while let Some(mat) = matches.peek() {
2903            let node = mat.captures[0].node;
2904            let start = Point::from_ts_point(node.start_position());
2905            let end = Point::from_ts_point(node.end_position());
2906            let range = start..end;
2907            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2908                Ok(ix) | Err(ix) => ix,
2909            };
2910            let mut end_ix = ix;
2911            while let Some(existing_range) = error_ranges.get(end_ix) {
2912                if existing_range.end < end {
2913                    end_ix += 1;
2914                } else {
2915                    break;
2916                }
2917            }
2918            error_ranges.splice(ix..end_ix, [range]);
2919            matches.advance();
2920        }
2921
2922        outdent_positions.sort();
2923        for outdent_position in outdent_positions {
2924            // find the innermost indent range containing this outdent_position
2925            // set its end to the outdent position
2926            if let Some(range_to_truncate) = indent_ranges
2927                .iter_mut()
2928                .filter(|indent_range| indent_range.contains(&outdent_position))
2929                .last()
2930            {
2931                range_to_truncate.end = outdent_position;
2932            }
2933        }
2934
2935        // Find the suggested indentation increases and decreased based on regexes.
2936        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2937        self.for_each_line(
2938            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2939                ..Point::new(row_range.end, 0),
2940            |row, line| {
2941                if config
2942                    .decrease_indent_pattern
2943                    .as_ref()
2944                    .map_or(false, |regex| regex.is_match(line))
2945                {
2946                    indent_change_rows.push((row, Ordering::Less));
2947                }
2948                if config
2949                    .increase_indent_pattern
2950                    .as_ref()
2951                    .map_or(false, |regex| regex.is_match(line))
2952                {
2953                    indent_change_rows.push((row + 1, Ordering::Greater));
2954                }
2955            },
2956        );
2957
2958        let mut indent_changes = indent_change_rows.into_iter().peekable();
2959        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2960            prev_non_blank_row.unwrap_or(0)
2961        } else {
2962            row_range.start.saturating_sub(1)
2963        };
2964        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2965        Some(row_range.map(move |row| {
2966            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2967
2968            let mut indent_from_prev_row = false;
2969            let mut outdent_from_prev_row = false;
2970            let mut outdent_to_row = u32::MAX;
2971            let mut from_regex = false;
2972
2973            while let Some((indent_row, delta)) = indent_changes.peek() {
2974                match indent_row.cmp(&row) {
2975                    Ordering::Equal => match delta {
2976                        Ordering::Less => {
2977                            from_regex = true;
2978                            outdent_from_prev_row = true
2979                        }
2980                        Ordering::Greater => {
2981                            indent_from_prev_row = true;
2982                            from_regex = true
2983                        }
2984                        _ => {}
2985                    },
2986
2987                    Ordering::Greater => break,
2988                    Ordering::Less => {}
2989                }
2990
2991                indent_changes.next();
2992            }
2993
2994            for range in &indent_ranges {
2995                if range.start.row >= row {
2996                    break;
2997                }
2998                if range.start.row == prev_row && range.end > row_start {
2999                    indent_from_prev_row = true;
3000                }
3001                if range.end > prev_row_start && range.end <= row_start {
3002                    outdent_to_row = outdent_to_row.min(range.start.row);
3003                }
3004            }
3005
3006            let within_error = error_ranges
3007                .iter()
3008                .any(|e| e.start.row < row && e.end > row_start);
3009
3010            let suggestion = if outdent_to_row == prev_row
3011                || (outdent_from_prev_row && indent_from_prev_row)
3012            {
3013                Some(IndentSuggestion {
3014                    basis_row: prev_row,
3015                    delta: Ordering::Equal,
3016                    within_error: within_error && !from_regex,
3017                })
3018            } else if indent_from_prev_row {
3019                Some(IndentSuggestion {
3020                    basis_row: prev_row,
3021                    delta: Ordering::Greater,
3022                    within_error: within_error && !from_regex,
3023                })
3024            } else if outdent_to_row < prev_row {
3025                Some(IndentSuggestion {
3026                    basis_row: outdent_to_row,
3027                    delta: Ordering::Equal,
3028                    within_error: within_error && !from_regex,
3029                })
3030            } else if outdent_from_prev_row {
3031                Some(IndentSuggestion {
3032                    basis_row: prev_row,
3033                    delta: Ordering::Less,
3034                    within_error: within_error && !from_regex,
3035                })
3036            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
3037            {
3038                Some(IndentSuggestion {
3039                    basis_row: prev_row,
3040                    delta: Ordering::Equal,
3041                    within_error: within_error && !from_regex,
3042                })
3043            } else {
3044                None
3045            };
3046
3047            prev_row = row;
3048            prev_row_start = row_start;
3049            suggestion
3050        }))
3051    }
3052
3053    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
3054        while row > 0 {
3055            row -= 1;
3056            if !self.is_line_blank(row) {
3057                return Some(row);
3058            }
3059        }
3060        None
3061    }
3062
3063    fn get_highlights(&self, range: Range<usize>) -> (SyntaxMapCaptures, Vec<HighlightMap>) {
3064        let captures = self.syntax.captures(range, &self.text, |grammar| {
3065            grammar.highlights_query.as_ref()
3066        });
3067        let highlight_maps = captures
3068            .grammars()
3069            .iter()
3070            .map(|grammar| grammar.highlight_map())
3071            .collect();
3072        (captures, highlight_maps)
3073    }
3074
3075    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
3076    /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
3077    /// returned in chunks where each chunk has a single syntax highlighting style and
3078    /// diagnostic status.
3079    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
3080        let range = range.start.to_offset(self)..range.end.to_offset(self);
3081
3082        let mut syntax = None;
3083        if language_aware {
3084            syntax = Some(self.get_highlights(range.clone()));
3085        }
3086        // We want to look at diagnostic spans only when iterating over language-annotated chunks.
3087        let diagnostics = language_aware;
3088        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostics, Some(self))
3089    }
3090
3091    pub fn highlighted_text_for_range<T: ToOffset>(
3092        &self,
3093        range: Range<T>,
3094        override_style: Option<HighlightStyle>,
3095        syntax_theme: &SyntaxTheme,
3096    ) -> HighlightedText {
3097        HighlightedText::from_buffer_range(
3098            range,
3099            &self.text,
3100            &self.syntax,
3101            override_style,
3102            syntax_theme,
3103        )
3104    }
3105
3106    /// Invokes the given callback for each line of text in the given range of the buffer.
3107    /// Uses callback to avoid allocating a string for each line.
3108    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
3109        let mut line = String::new();
3110        let mut row = range.start.row;
3111        for chunk in self
3112            .as_rope()
3113            .chunks_in_range(range.to_offset(self))
3114            .chain(["\n"])
3115        {
3116            for (newline_ix, text) in chunk.split('\n').enumerate() {
3117                if newline_ix > 0 {
3118                    callback(row, &line);
3119                    row += 1;
3120                    line.clear();
3121                }
3122                line.push_str(text);
3123            }
3124        }
3125    }
3126
3127    /// Iterates over every [`SyntaxLayer`] in the buffer.
3128    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
3129        self.syntax
3130            .layers_for_range(0..self.len(), &self.text, true)
3131    }
3132
3133    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
3134        let offset = position.to_offset(self);
3135        self.syntax
3136            .layers_for_range(offset..offset, &self.text, false)
3137            .filter(|l| l.node().end_byte() > offset)
3138            .last()
3139    }
3140
3141    pub fn smallest_syntax_layer_containing<D: ToOffset>(
3142        &self,
3143        range: Range<D>,
3144    ) -> Option<SyntaxLayer> {
3145        let range = range.to_offset(self);
3146        return self
3147            .syntax
3148            .layers_for_range(range, &self.text, false)
3149            .max_by(|a, b| {
3150                if a.depth != b.depth {
3151                    a.depth.cmp(&b.depth)
3152                } else if a.offset.0 != b.offset.0 {
3153                    a.offset.0.cmp(&b.offset.0)
3154                } else {
3155                    a.node().end_byte().cmp(&b.node().end_byte()).reverse()
3156                }
3157            });
3158    }
3159
3160    /// Returns the main [`Language`].
3161    pub fn language(&self) -> Option<&Arc<Language>> {
3162        self.language.as_ref()
3163    }
3164
3165    /// Returns the [`Language`] at the given location.
3166    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
3167        self.syntax_layer_at(position)
3168            .map(|info| info.language)
3169            .or(self.language.as_ref())
3170    }
3171
3172    /// Returns the settings for the language at the given location.
3173    pub fn settings_at<'a, D: ToOffset>(
3174        &'a self,
3175        position: D,
3176        cx: &'a App,
3177    ) -> Cow<'a, LanguageSettings> {
3178        language_settings(
3179            self.language_at(position).map(|l| l.name()),
3180            self.file.as_ref(),
3181            cx,
3182        )
3183    }
3184
3185    pub fn char_classifier_at<T: ToOffset>(&self, point: T) -> CharClassifier {
3186        CharClassifier::new(self.language_scope_at(point))
3187    }
3188
3189    /// Returns the [`LanguageScope`] at the given location.
3190    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
3191        let offset = position.to_offset(self);
3192        let mut scope = None;
3193        let mut smallest_range: Option<Range<usize>> = None;
3194
3195        // Use the layer that has the smallest node intersecting the given point.
3196        for layer in self
3197            .syntax
3198            .layers_for_range(offset..offset, &self.text, false)
3199        {
3200            let mut cursor = layer.node().walk();
3201
3202            let mut range = None;
3203            loop {
3204                let child_range = cursor.node().byte_range();
3205                if !child_range.to_inclusive().contains(&offset) {
3206                    break;
3207                }
3208
3209                range = Some(child_range);
3210                if cursor.goto_first_child_for_byte(offset).is_none() {
3211                    break;
3212                }
3213            }
3214
3215            if let Some(range) = range {
3216                if smallest_range
3217                    .as_ref()
3218                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
3219                {
3220                    smallest_range = Some(range);
3221                    scope = Some(LanguageScope {
3222                        language: layer.language.clone(),
3223                        override_id: layer.override_id(offset, &self.text),
3224                    });
3225                }
3226            }
3227        }
3228
3229        scope.or_else(|| {
3230            self.language.clone().map(|language| LanguageScope {
3231                language,
3232                override_id: None,
3233            })
3234        })
3235    }
3236
3237    /// Returns a tuple of the range and character kind of the word
3238    /// surrounding the given position.
3239    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
3240        let mut start = start.to_offset(self);
3241        let mut end = start;
3242        let mut next_chars = self.chars_at(start).peekable();
3243        let mut prev_chars = self.reversed_chars_at(start).peekable();
3244
3245        let classifier = self.char_classifier_at(start);
3246        let word_kind = cmp::max(
3247            prev_chars.peek().copied().map(|c| classifier.kind(c)),
3248            next_chars.peek().copied().map(|c| classifier.kind(c)),
3249        );
3250
3251        for ch in prev_chars {
3252            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3253                start -= ch.len_utf8();
3254            } else {
3255                break;
3256            }
3257        }
3258
3259        for ch in next_chars {
3260            if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
3261                end += ch.len_utf8();
3262            } else {
3263                break;
3264            }
3265        }
3266
3267        (start..end, word_kind)
3268    }
3269
3270    /// Returns the closest syntax node enclosing the given range.
3271    pub fn syntax_ancestor<'a, T: ToOffset>(
3272        &'a self,
3273        range: Range<T>,
3274    ) -> Option<tree_sitter::Node<'a>> {
3275        let range = range.start.to_offset(self)..range.end.to_offset(self);
3276        let mut result: Option<tree_sitter::Node<'a>> = None;
3277        'outer: for layer in self
3278            .syntax
3279            .layers_for_range(range.clone(), &self.text, true)
3280        {
3281            let mut cursor = layer.node().walk();
3282
3283            // Descend to the first leaf that touches the start of the range,
3284            // and if the range is non-empty, extends beyond the start.
3285            while cursor.goto_first_child_for_byte(range.start).is_some() {
3286                if !range.is_empty() && cursor.node().end_byte() == range.start {
3287                    cursor.goto_next_sibling();
3288                }
3289            }
3290
3291            // Ascend to the smallest ancestor that strictly contains the range.
3292            loop {
3293                let node_range = cursor.node().byte_range();
3294                if node_range.start <= range.start
3295                    && node_range.end >= range.end
3296                    && node_range.len() > range.len()
3297                {
3298                    break;
3299                }
3300                if !cursor.goto_parent() {
3301                    continue 'outer;
3302                }
3303            }
3304
3305            let left_node = cursor.node();
3306            let mut layer_result = left_node;
3307
3308            // For an empty range, try to find another node immediately to the right of the range.
3309            if left_node.end_byte() == range.start {
3310                let mut right_node = None;
3311                while !cursor.goto_next_sibling() {
3312                    if !cursor.goto_parent() {
3313                        break;
3314                    }
3315                }
3316
3317                while cursor.node().start_byte() == range.start {
3318                    right_node = Some(cursor.node());
3319                    if !cursor.goto_first_child() {
3320                        break;
3321                    }
3322                }
3323
3324                // If there is a candidate node on both sides of the (empty) range, then
3325                // decide between the two by favoring a named node over an anonymous token.
3326                // If both nodes are the same in that regard, favor the right one.
3327                if let Some(right_node) = right_node {
3328                    if right_node.is_named() || !left_node.is_named() {
3329                        layer_result = right_node;
3330                    }
3331                }
3332            }
3333
3334            if let Some(previous_result) = &result {
3335                if previous_result.byte_range().len() < layer_result.byte_range().len() {
3336                    continue;
3337                }
3338            }
3339            result = Some(layer_result);
3340        }
3341
3342        result
3343    }
3344
3345    /// Returns the outline for the buffer.
3346    ///
3347    /// This method allows passing an optional [`SyntaxTheme`] to
3348    /// syntax-highlight the returned symbols.
3349    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3350        self.outline_items_containing(0..self.len(), true, theme)
3351            .map(Outline::new)
3352    }
3353
3354    /// Returns all the symbols that contain the given position.
3355    ///
3356    /// This method allows passing an optional [`SyntaxTheme`] to
3357    /// syntax-highlight the returned symbols.
3358    pub fn symbols_containing<T: ToOffset>(
3359        &self,
3360        position: T,
3361        theme: Option<&SyntaxTheme>,
3362    ) -> Option<Vec<OutlineItem<Anchor>>> {
3363        let position = position.to_offset(self);
3364        let mut items = self.outline_items_containing(
3365            position.saturating_sub(1)..self.len().min(position + 1),
3366            false,
3367            theme,
3368        )?;
3369        let mut prev_depth = None;
3370        items.retain(|item| {
3371            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
3372            prev_depth = Some(item.depth);
3373            result
3374        });
3375        Some(items)
3376    }
3377
3378    pub fn outline_range_containing<T: ToOffset>(&self, range: Range<T>) -> Option<Range<Point>> {
3379        let range = range.to_offset(self);
3380        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3381            grammar.outline_config.as_ref().map(|c| &c.query)
3382        });
3383        let configs = matches
3384            .grammars()
3385            .iter()
3386            .map(|g| g.outline_config.as_ref().unwrap())
3387            .collect::<Vec<_>>();
3388
3389        while let Some(mat) = matches.peek() {
3390            let config = &configs[mat.grammar_index];
3391            let containing_item_node = maybe!({
3392                let item_node = mat.captures.iter().find_map(|cap| {
3393                    if cap.index == config.item_capture_ix {
3394                        Some(cap.node)
3395                    } else {
3396                        None
3397                    }
3398                })?;
3399
3400                let item_byte_range = item_node.byte_range();
3401                if item_byte_range.end < range.start || item_byte_range.start > range.end {
3402                    None
3403                } else {
3404                    Some(item_node)
3405                }
3406            });
3407
3408            if let Some(item_node) = containing_item_node {
3409                return Some(
3410                    Point::from_ts_point(item_node.start_position())
3411                        ..Point::from_ts_point(item_node.end_position()),
3412                );
3413            }
3414
3415            matches.advance();
3416        }
3417        None
3418    }
3419
3420    pub fn outline_items_containing<T: ToOffset>(
3421        &self,
3422        range: Range<T>,
3423        include_extra_context: bool,
3424        theme: Option<&SyntaxTheme>,
3425    ) -> Option<Vec<OutlineItem<Anchor>>> {
3426        let range = range.to_offset(self);
3427        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3428            grammar.outline_config.as_ref().map(|c| &c.query)
3429        });
3430        let configs = matches
3431            .grammars()
3432            .iter()
3433            .map(|g| g.outline_config.as_ref().unwrap())
3434            .collect::<Vec<_>>();
3435
3436        let mut items = Vec::new();
3437        let mut annotation_row_ranges: Vec<Range<u32>> = Vec::new();
3438        while let Some(mat) = matches.peek() {
3439            let config = &configs[mat.grammar_index];
3440            if let Some(item) =
3441                self.next_outline_item(config, &mat, &range, include_extra_context, theme)
3442            {
3443                items.push(item);
3444            } else if let Some(capture) = mat
3445                .captures
3446                .iter()
3447                .find(|capture| Some(capture.index) == config.annotation_capture_ix)
3448            {
3449                let capture_range = capture.node.start_position()..capture.node.end_position();
3450                let mut capture_row_range =
3451                    capture_range.start.row as u32..capture_range.end.row as u32;
3452                if capture_range.end.row > capture_range.start.row && capture_range.end.column == 0
3453                {
3454                    capture_row_range.end -= 1;
3455                }
3456                if let Some(last_row_range) = annotation_row_ranges.last_mut() {
3457                    if last_row_range.end >= capture_row_range.start.saturating_sub(1) {
3458                        last_row_range.end = capture_row_range.end;
3459                    } else {
3460                        annotation_row_ranges.push(capture_row_range);
3461                    }
3462                } else {
3463                    annotation_row_ranges.push(capture_row_range);
3464                }
3465            }
3466            matches.advance();
3467        }
3468
3469        items.sort_by_key(|item| (item.range.start, Reverse(item.range.end)));
3470
3471        // Assign depths based on containment relationships and convert to anchors.
3472        let mut item_ends_stack = Vec::<Point>::new();
3473        let mut anchor_items = Vec::new();
3474        let mut annotation_row_ranges = annotation_row_ranges.into_iter().peekable();
3475        for item in items {
3476            while let Some(last_end) = item_ends_stack.last().copied() {
3477                if last_end < item.range.end {
3478                    item_ends_stack.pop();
3479                } else {
3480                    break;
3481                }
3482            }
3483
3484            let mut annotation_row_range = None;
3485            while let Some(next_annotation_row_range) = annotation_row_ranges.peek() {
3486                let row_preceding_item = item.range.start.row.saturating_sub(1);
3487                if next_annotation_row_range.end < row_preceding_item {
3488                    annotation_row_ranges.next();
3489                } else {
3490                    if next_annotation_row_range.end == row_preceding_item {
3491                        annotation_row_range = Some(next_annotation_row_range.clone());
3492                        annotation_row_ranges.next();
3493                    }
3494                    break;
3495                }
3496            }
3497
3498            anchor_items.push(OutlineItem {
3499                depth: item_ends_stack.len(),
3500                range: self.anchor_after(item.range.start)..self.anchor_before(item.range.end),
3501                text: item.text,
3502                highlight_ranges: item.highlight_ranges,
3503                name_ranges: item.name_ranges,
3504                body_range: item.body_range.map(|body_range| {
3505                    self.anchor_after(body_range.start)..self.anchor_before(body_range.end)
3506                }),
3507                annotation_range: annotation_row_range.map(|annotation_range| {
3508                    self.anchor_after(Point::new(annotation_range.start, 0))
3509                        ..self.anchor_before(Point::new(
3510                            annotation_range.end,
3511                            self.line_len(annotation_range.end),
3512                        ))
3513                }),
3514            });
3515            item_ends_stack.push(item.range.end);
3516        }
3517
3518        Some(anchor_items)
3519    }
3520
3521    fn next_outline_item(
3522        &self,
3523        config: &OutlineConfig,
3524        mat: &SyntaxMapMatch,
3525        range: &Range<usize>,
3526        include_extra_context: bool,
3527        theme: Option<&SyntaxTheme>,
3528    ) -> Option<OutlineItem<Point>> {
3529        let item_node = mat.captures.iter().find_map(|cap| {
3530            if cap.index == config.item_capture_ix {
3531                Some(cap.node)
3532            } else {
3533                None
3534            }
3535        })?;
3536
3537        let item_byte_range = item_node.byte_range();
3538        if item_byte_range.end < range.start || item_byte_range.start > range.end {
3539            return None;
3540        }
3541        let item_point_range = Point::from_ts_point(item_node.start_position())
3542            ..Point::from_ts_point(item_node.end_position());
3543
3544        let mut open_point = None;
3545        let mut close_point = None;
3546        let mut buffer_ranges = Vec::new();
3547        for capture in mat.captures {
3548            let node_is_name;
3549            if capture.index == config.name_capture_ix {
3550                node_is_name = true;
3551            } else if Some(capture.index) == config.context_capture_ix
3552                || (Some(capture.index) == config.extra_context_capture_ix && include_extra_context)
3553            {
3554                node_is_name = false;
3555            } else {
3556                if Some(capture.index) == config.open_capture_ix {
3557                    open_point = Some(Point::from_ts_point(capture.node.end_position()));
3558                } else if Some(capture.index) == config.close_capture_ix {
3559                    close_point = Some(Point::from_ts_point(capture.node.start_position()));
3560                }
3561
3562                continue;
3563            }
3564
3565            let mut range = capture.node.start_byte()..capture.node.end_byte();
3566            let start = capture.node.start_position();
3567            if capture.node.end_position().row > start.row {
3568                range.end = range.start + self.line_len(start.row as u32) as usize - start.column;
3569            }
3570
3571            if !range.is_empty() {
3572                buffer_ranges.push((range, node_is_name));
3573            }
3574        }
3575        if buffer_ranges.is_empty() {
3576            return None;
3577        }
3578        let mut text = String::new();
3579        let mut highlight_ranges = Vec::new();
3580        let mut name_ranges = Vec::new();
3581        let mut chunks = self.chunks(
3582            buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
3583            true,
3584        );
3585        let mut last_buffer_range_end = 0;
3586
3587        for (buffer_range, is_name) in buffer_ranges {
3588            let space_added = !text.is_empty() && buffer_range.start > last_buffer_range_end;
3589            if space_added {
3590                text.push(' ');
3591            }
3592            let before_append_len = text.len();
3593            let mut offset = buffer_range.start;
3594            chunks.seek(buffer_range.clone());
3595            for mut chunk in chunks.by_ref() {
3596                if chunk.text.len() > buffer_range.end - offset {
3597                    chunk.text = &chunk.text[0..(buffer_range.end - offset)];
3598                    offset = buffer_range.end;
3599                } else {
3600                    offset += chunk.text.len();
3601                }
3602                let style = chunk
3603                    .syntax_highlight_id
3604                    .zip(theme)
3605                    .and_then(|(highlight, theme)| highlight.style(theme));
3606                if let Some(style) = style {
3607                    let start = text.len();
3608                    let end = start + chunk.text.len();
3609                    highlight_ranges.push((start..end, style));
3610                }
3611                text.push_str(chunk.text);
3612                if offset >= buffer_range.end {
3613                    break;
3614                }
3615            }
3616            if is_name {
3617                let after_append_len = text.len();
3618                let start = if space_added && !name_ranges.is_empty() {
3619                    before_append_len - 1
3620                } else {
3621                    before_append_len
3622                };
3623                name_ranges.push(start..after_append_len);
3624            }
3625            last_buffer_range_end = buffer_range.end;
3626        }
3627
3628        Some(OutlineItem {
3629            depth: 0, // We'll calculate the depth later
3630            range: item_point_range,
3631            text,
3632            highlight_ranges,
3633            name_ranges,
3634            body_range: open_point.zip(close_point).map(|(start, end)| start..end),
3635            annotation_range: None,
3636        })
3637    }
3638
3639    pub fn function_body_fold_ranges<T: ToOffset>(
3640        &self,
3641        within: Range<T>,
3642    ) -> impl Iterator<Item = Range<usize>> + '_ {
3643        self.text_object_ranges(within, TreeSitterOptions::default())
3644            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
3645    }
3646
3647    /// For each grammar in the language, runs the provided
3648    /// [`tree_sitter::Query`] against the given range.
3649    pub fn matches(
3650        &self,
3651        range: Range<usize>,
3652        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
3653    ) -> SyntaxMapMatches {
3654        self.syntax.matches(range, self, query)
3655    }
3656
3657    pub fn all_bracket_ranges(
3658        &self,
3659        range: Range<usize>,
3660    ) -> impl Iterator<Item = BracketMatch> + '_ {
3661        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
3662            grammar.brackets_config.as_ref().map(|c| &c.query)
3663        });
3664        let configs = matches
3665            .grammars()
3666            .iter()
3667            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
3668            .collect::<Vec<_>>();
3669
3670        iter::from_fn(move || {
3671            while let Some(mat) = matches.peek() {
3672                let mut open = None;
3673                let mut close = None;
3674                let config = &configs[mat.grammar_index];
3675                let pattern = &config.patterns[mat.pattern_index];
3676                for capture in mat.captures {
3677                    if capture.index == config.open_capture_ix {
3678                        open = Some(capture.node.byte_range());
3679                    } else if capture.index == config.close_capture_ix {
3680                        close = Some(capture.node.byte_range());
3681                    }
3682                }
3683
3684                matches.advance();
3685
3686                let Some((open_range, close_range)) = open.zip(close) else {
3687                    continue;
3688                };
3689
3690                let bracket_range = open_range.start..=close_range.end;
3691                if !bracket_range.overlaps(&range) {
3692                    continue;
3693                }
3694
3695                return Some(BracketMatch {
3696                    open_range,
3697                    close_range,
3698                    newline_only: pattern.newline_only,
3699                });
3700            }
3701            None
3702        })
3703    }
3704
3705    /// Returns bracket range pairs overlapping or adjacent to `range`
3706    pub fn bracket_ranges<T: ToOffset>(
3707        &self,
3708        range: Range<T>,
3709    ) -> impl Iterator<Item = BracketMatch> + '_ {
3710        // Find bracket pairs that *inclusively* contain the given range.
3711        let range = range.start.to_offset(self).saturating_sub(1)
3712            ..self.len().min(range.end.to_offset(self) + 1);
3713        self.all_bracket_ranges(range)
3714            .filter(|pair| !pair.newline_only)
3715    }
3716
3717    pub fn text_object_ranges<T: ToOffset>(
3718        &self,
3719        range: Range<T>,
3720        options: TreeSitterOptions,
3721    ) -> impl Iterator<Item = (Range<usize>, TextObject)> + '_ {
3722        let range = range.start.to_offset(self).saturating_sub(1)
3723            ..self.len().min(range.end.to_offset(self) + 1);
3724
3725        let mut matches =
3726            self.syntax
3727                .matches_with_options(range.clone(), &self.text, options, |grammar| {
3728                    grammar.text_object_config.as_ref().map(|c| &c.query)
3729                });
3730
3731        let configs = matches
3732            .grammars()
3733            .iter()
3734            .map(|grammar| grammar.text_object_config.as_ref())
3735            .collect::<Vec<_>>();
3736
3737        let mut captures = Vec::<(Range<usize>, TextObject)>::new();
3738
3739        iter::from_fn(move || loop {
3740            while let Some(capture) = captures.pop() {
3741                if capture.0.overlaps(&range) {
3742                    return Some(capture);
3743                }
3744            }
3745
3746            let mat = matches.peek()?;
3747
3748            let Some(config) = configs[mat.grammar_index].as_ref() else {
3749                matches.advance();
3750                continue;
3751            };
3752
3753            for capture in mat.captures {
3754                let Some(ix) = config
3755                    .text_objects_by_capture_ix
3756                    .binary_search_by_key(&capture.index, |e| e.0)
3757                    .ok()
3758                else {
3759                    continue;
3760                };
3761                let text_object = config.text_objects_by_capture_ix[ix].1;
3762                let byte_range = capture.node.byte_range();
3763
3764                let mut found = false;
3765                for (range, existing) in captures.iter_mut() {
3766                    if existing == &text_object {
3767                        range.start = range.start.min(byte_range.start);
3768                        range.end = range.end.max(byte_range.end);
3769                        found = true;
3770                        break;
3771                    }
3772                }
3773
3774                if !found {
3775                    captures.push((byte_range, text_object));
3776                }
3777            }
3778
3779            matches.advance();
3780        })
3781    }
3782
3783    /// Returns enclosing bracket ranges containing the given range
3784    pub fn enclosing_bracket_ranges<T: ToOffset>(
3785        &self,
3786        range: Range<T>,
3787    ) -> impl Iterator<Item = BracketMatch> + '_ {
3788        let range = range.start.to_offset(self)..range.end.to_offset(self);
3789
3790        self.bracket_ranges(range.clone()).filter(move |pair| {
3791            pair.open_range.start <= range.start && pair.close_range.end >= range.end
3792        })
3793    }
3794
3795    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3796    ///
3797    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3798    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3799        &self,
3800        range: Range<T>,
3801        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3802    ) -> Option<(Range<usize>, Range<usize>)> {
3803        let range = range.start.to_offset(self)..range.end.to_offset(self);
3804
3805        // Get the ranges of the innermost pair of brackets.
3806        let mut result: Option<(Range<usize>, Range<usize>)> = None;
3807
3808        for pair in self.enclosing_bracket_ranges(range.clone()) {
3809            if let Some(range_filter) = range_filter {
3810                if !range_filter(pair.open_range.clone(), pair.close_range.clone()) {
3811                    continue;
3812                }
3813            }
3814
3815            let len = pair.close_range.end - pair.open_range.start;
3816
3817            if let Some((existing_open, existing_close)) = &result {
3818                let existing_len = existing_close.end - existing_open.start;
3819                if len > existing_len {
3820                    continue;
3821                }
3822            }
3823
3824            result = Some((pair.open_range, pair.close_range));
3825        }
3826
3827        result
3828    }
3829
3830    /// Returns anchor ranges for any matches of the redaction query.
3831    /// The buffer can be associated with multiple languages, and the redaction query associated with each
3832    /// will be run on the relevant section of the buffer.
3833    pub fn redacted_ranges<T: ToOffset>(
3834        &self,
3835        range: Range<T>,
3836    ) -> impl Iterator<Item = Range<usize>> + '_ {
3837        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3838        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3839            grammar
3840                .redactions_config
3841                .as_ref()
3842                .map(|config| &config.query)
3843        });
3844
3845        let configs = syntax_matches
3846            .grammars()
3847            .iter()
3848            .map(|grammar| grammar.redactions_config.as_ref())
3849            .collect::<Vec<_>>();
3850
3851        iter::from_fn(move || {
3852            let redacted_range = syntax_matches
3853                .peek()
3854                .and_then(|mat| {
3855                    configs[mat.grammar_index].and_then(|config| {
3856                        mat.captures
3857                            .iter()
3858                            .find(|capture| capture.index == config.redaction_capture_ix)
3859                    })
3860                })
3861                .map(|mat| mat.node.byte_range());
3862            syntax_matches.advance();
3863            redacted_range
3864        })
3865    }
3866
3867    pub fn injections_intersecting_range<T: ToOffset>(
3868        &self,
3869        range: Range<T>,
3870    ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3871        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3872
3873        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3874            grammar
3875                .injection_config
3876                .as_ref()
3877                .map(|config| &config.query)
3878        });
3879
3880        let configs = syntax_matches
3881            .grammars()
3882            .iter()
3883            .map(|grammar| grammar.injection_config.as_ref())
3884            .collect::<Vec<_>>();
3885
3886        iter::from_fn(move || {
3887            let ranges = syntax_matches.peek().and_then(|mat| {
3888                let config = &configs[mat.grammar_index]?;
3889                let content_capture_range = mat.captures.iter().find_map(|capture| {
3890                    if capture.index == config.content_capture_ix {
3891                        Some(capture.node.byte_range())
3892                    } else {
3893                        None
3894                    }
3895                })?;
3896                let language = self.language_at(content_capture_range.start)?;
3897                Some((content_capture_range, language))
3898            });
3899            syntax_matches.advance();
3900            ranges
3901        })
3902    }
3903
3904    pub fn runnable_ranges(
3905        &self,
3906        offset_range: Range<usize>,
3907    ) -> impl Iterator<Item = RunnableRange> + '_ {
3908        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3909            grammar.runnable_config.as_ref().map(|config| &config.query)
3910        });
3911
3912        let test_configs = syntax_matches
3913            .grammars()
3914            .iter()
3915            .map(|grammar| grammar.runnable_config.as_ref())
3916            .collect::<Vec<_>>();
3917
3918        iter::from_fn(move || loop {
3919            let mat = syntax_matches.peek()?;
3920
3921            let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3922                let mut run_range = None;
3923                let full_range = mat.captures.iter().fold(
3924                    Range {
3925                        start: usize::MAX,
3926                        end: 0,
3927                    },
3928                    |mut acc, next| {
3929                        let byte_range = next.node.byte_range();
3930                        if acc.start > byte_range.start {
3931                            acc.start = byte_range.start;
3932                        }
3933                        if acc.end < byte_range.end {
3934                            acc.end = byte_range.end;
3935                        }
3936                        acc
3937                    },
3938                );
3939                if full_range.start > full_range.end {
3940                    // We did not find a full spanning range of this match.
3941                    return None;
3942                }
3943                let extra_captures: SmallVec<[_; 1]> =
3944                    SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3945                        test_configs
3946                            .extra_captures
3947                            .get(capture.index as usize)
3948                            .cloned()
3949                            .and_then(|tag_name| match tag_name {
3950                                RunnableCapture::Named(name) => {
3951                                    Some((capture.node.byte_range(), name))
3952                                }
3953                                RunnableCapture::Run => {
3954                                    let _ = run_range.insert(capture.node.byte_range());
3955                                    None
3956                                }
3957                            })
3958                    }));
3959                let run_range = run_range?;
3960                let tags = test_configs
3961                    .query
3962                    .property_settings(mat.pattern_index)
3963                    .iter()
3964                    .filter_map(|property| {
3965                        if *property.key == *"tag" {
3966                            property
3967                                .value
3968                                .as_ref()
3969                                .map(|value| RunnableTag(value.to_string().into()))
3970                        } else {
3971                            None
3972                        }
3973                    })
3974                    .collect();
3975                let extra_captures = extra_captures
3976                    .into_iter()
3977                    .map(|(range, name)| {
3978                        (
3979                            name.to_string(),
3980                            self.text_for_range(range.clone()).collect::<String>(),
3981                        )
3982                    })
3983                    .collect();
3984                // All tags should have the same range.
3985                Some(RunnableRange {
3986                    run_range,
3987                    full_range,
3988                    runnable: Runnable {
3989                        tags,
3990                        language: mat.language,
3991                        buffer: self.remote_id(),
3992                    },
3993                    extra_captures,
3994                    buffer_id: self.remote_id(),
3995                })
3996            });
3997
3998            syntax_matches.advance();
3999            if test_range.is_some() {
4000                // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
4001                // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
4002                return test_range;
4003            }
4004        })
4005    }
4006
4007    /// Returns selections for remote peers intersecting the given range.
4008    #[allow(clippy::type_complexity)]
4009    pub fn selections_in_range(
4010        &self,
4011        range: Range<Anchor>,
4012        include_local: bool,
4013    ) -> impl Iterator<
4014        Item = (
4015            ReplicaId,
4016            bool,
4017            CursorShape,
4018            impl Iterator<Item = &Selection<Anchor>> + '_,
4019        ),
4020    > + '_ {
4021        self.remote_selections
4022            .iter()
4023            .filter(move |(replica_id, set)| {
4024                (include_local || **replica_id != self.text.replica_id())
4025                    && !set.selections.is_empty()
4026            })
4027            .map(move |(replica_id, set)| {
4028                let start_ix = match set.selections.binary_search_by(|probe| {
4029                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
4030                }) {
4031                    Ok(ix) | Err(ix) => ix,
4032                };
4033                let end_ix = match set.selections.binary_search_by(|probe| {
4034                    probe.start.cmp(&range.end, self).then(Ordering::Less)
4035                }) {
4036                    Ok(ix) | Err(ix) => ix,
4037                };
4038
4039                (
4040                    *replica_id,
4041                    set.line_mode,
4042                    set.cursor_shape,
4043                    set.selections[start_ix..end_ix].iter(),
4044                )
4045            })
4046    }
4047
4048    /// Returns if the buffer contains any diagnostics.
4049    pub fn has_diagnostics(&self) -> bool {
4050        !self.diagnostics.is_empty()
4051    }
4052
4053    /// Returns all the diagnostics intersecting the given range.
4054    pub fn diagnostics_in_range<'a, T, O>(
4055        &'a self,
4056        search_range: Range<T>,
4057        reversed: bool,
4058    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
4059    where
4060        T: 'a + Clone + ToOffset,
4061        O: 'a + FromAnchor,
4062    {
4063        let mut iterators: Vec<_> = self
4064            .diagnostics
4065            .iter()
4066            .map(|(_, collection)| {
4067                collection
4068                    .range::<T, text::Anchor>(search_range.clone(), self, true, reversed)
4069                    .peekable()
4070            })
4071            .collect();
4072
4073        std::iter::from_fn(move || {
4074            let (next_ix, _) = iterators
4075                .iter_mut()
4076                .enumerate()
4077                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
4078                .min_by(|(_, a), (_, b)| {
4079                    let cmp = a
4080                        .range
4081                        .start
4082                        .cmp(&b.range.start, self)
4083                        // when range is equal, sort by diagnostic severity
4084                        .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
4085                        // and stabilize order with group_id
4086                        .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
4087                    if reversed {
4088                        cmp.reverse()
4089                    } else {
4090                        cmp
4091                    }
4092                })?;
4093            iterators[next_ix]
4094                .next()
4095                .map(|DiagnosticEntry { range, diagnostic }| DiagnosticEntry {
4096                    diagnostic,
4097                    range: FromAnchor::from_anchor(&range.start, self)
4098                        ..FromAnchor::from_anchor(&range.end, self),
4099                })
4100        })
4101    }
4102
4103    /// Returns all the diagnostic groups associated with the given
4104    /// language server ID. If no language server ID is provided,
4105    /// all diagnostics groups are returned.
4106    pub fn diagnostic_groups(
4107        &self,
4108        language_server_id: Option<LanguageServerId>,
4109    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
4110        let mut groups = Vec::new();
4111
4112        if let Some(language_server_id) = language_server_id {
4113            if let Ok(ix) = self
4114                .diagnostics
4115                .binary_search_by_key(&language_server_id, |e| e.0)
4116            {
4117                self.diagnostics[ix]
4118                    .1
4119                    .groups(language_server_id, &mut groups, self);
4120            }
4121        } else {
4122            for (language_server_id, diagnostics) in self.diagnostics.iter() {
4123                diagnostics.groups(*language_server_id, &mut groups, self);
4124            }
4125        }
4126
4127        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
4128            let a_start = &group_a.entries[group_a.primary_ix].range.start;
4129            let b_start = &group_b.entries[group_b.primary_ix].range.start;
4130            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
4131        });
4132
4133        groups
4134    }
4135
4136    /// Returns an iterator over the diagnostics for the given group.
4137    pub fn diagnostic_group<O>(
4138        &self,
4139        group_id: usize,
4140    ) -> impl Iterator<Item = DiagnosticEntry<O>> + '_
4141    where
4142        O: FromAnchor + 'static,
4143    {
4144        self.diagnostics
4145            .iter()
4146            .flat_map(move |(_, set)| set.group(group_id, self))
4147    }
4148
4149    /// An integer version number that accounts for all updates besides
4150    /// the buffer's text itself (which is versioned via a version vector).
4151    pub fn non_text_state_update_count(&self) -> usize {
4152        self.non_text_state_update_count
4153    }
4154
4155    /// Returns a snapshot of underlying file.
4156    pub fn file(&self) -> Option<&Arc<dyn File>> {
4157        self.file.as_ref()
4158    }
4159
4160    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
4161    pub fn resolve_file_path(&self, cx: &App, include_root: bool) -> Option<PathBuf> {
4162        if let Some(file) = self.file() {
4163            if file.path().file_name().is_none() || include_root {
4164                Some(file.full_path(cx))
4165            } else {
4166                Some(file.path().to_path_buf())
4167            }
4168        } else {
4169            None
4170        }
4171    }
4172
4173    pub fn words_in_range(&self, query: WordsQuery) -> HashMap<String, Range<Anchor>> {
4174        let query_str = query.fuzzy_contents;
4175        if query_str.map_or(false, |query| query.is_empty()) {
4176            return HashMap::default();
4177        }
4178
4179        let classifier = CharClassifier::new(self.language.clone().map(|language| LanguageScope {
4180            language,
4181            override_id: None,
4182        }));
4183
4184        let mut query_ix = 0;
4185        let query_chars = query_str.map(|query| query.chars().collect::<Vec<_>>());
4186        let query_len = query_chars.as_ref().map_or(0, |query| query.len());
4187
4188        let mut words = HashMap::default();
4189        let mut current_word_start_ix = None;
4190        let mut chunk_ix = query.range.start;
4191        for chunk in self.chunks(query.range, false) {
4192            for (i, c) in chunk.text.char_indices() {
4193                let ix = chunk_ix + i;
4194                if classifier.is_word(c) {
4195                    if current_word_start_ix.is_none() {
4196                        current_word_start_ix = Some(ix);
4197                    }
4198
4199                    if let Some(query_chars) = &query_chars {
4200                        if query_ix < query_len {
4201                            if c.to_lowercase().eq(query_chars[query_ix].to_lowercase()) {
4202                                query_ix += 1;
4203                            }
4204                        }
4205                    }
4206                    continue;
4207                } else if let Some(word_start) = current_word_start_ix.take() {
4208                    if query_ix == query_len {
4209                        let word_range = self.anchor_before(word_start)..self.anchor_after(ix);
4210                        let mut word_text = self.text_for_range(word_start..ix).peekable();
4211                        let first_char = word_text
4212                            .peek()
4213                            .and_then(|first_chunk| first_chunk.chars().next());
4214                        // Skip empty and "words" starting with digits as a heuristic to reduce useless completions
4215                        if !query.skip_digits
4216                            || first_char.map_or(true, |first_char| !first_char.is_digit(10))
4217                        {
4218                            words.insert(word_text.collect(), word_range);
4219                        }
4220                    }
4221                }
4222                query_ix = 0;
4223            }
4224            chunk_ix += chunk.text.len();
4225        }
4226
4227        words
4228    }
4229}
4230
4231pub struct WordsQuery<'a> {
4232    /// Only returns words with all chars from the fuzzy string in them.
4233    pub fuzzy_contents: Option<&'a str>,
4234    /// Skips words that start with a digit.
4235    pub skip_digits: bool,
4236    /// Buffer offset range, to look for words.
4237    pub range: Range<usize>,
4238}
4239
4240fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
4241    indent_size_for_text(text.chars_at(Point::new(row, 0)))
4242}
4243
4244fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
4245    let mut result = IndentSize::spaces(0);
4246    for c in text {
4247        let kind = match c {
4248            ' ' => IndentKind::Space,
4249            '\t' => IndentKind::Tab,
4250            _ => break,
4251        };
4252        if result.len == 0 {
4253            result.kind = kind;
4254        }
4255        result.len += 1;
4256    }
4257    result
4258}
4259
4260impl Clone for BufferSnapshot {
4261    fn clone(&self) -> Self {
4262        Self {
4263            text: self.text.clone(),
4264            syntax: self.syntax.clone(),
4265            file: self.file.clone(),
4266            remote_selections: self.remote_selections.clone(),
4267            diagnostics: self.diagnostics.clone(),
4268            language: self.language.clone(),
4269            non_text_state_update_count: self.non_text_state_update_count,
4270        }
4271    }
4272}
4273
4274impl Deref for BufferSnapshot {
4275    type Target = text::BufferSnapshot;
4276
4277    fn deref(&self) -> &Self::Target {
4278        &self.text
4279    }
4280}
4281
4282unsafe impl Send for BufferChunks<'_> {}
4283
4284impl<'a> BufferChunks<'a> {
4285    pub(crate) fn new(
4286        text: &'a Rope,
4287        range: Range<usize>,
4288        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
4289        diagnostics: bool,
4290        buffer_snapshot: Option<&'a BufferSnapshot>,
4291    ) -> Self {
4292        let mut highlights = None;
4293        if let Some((captures, highlight_maps)) = syntax {
4294            highlights = Some(BufferChunkHighlights {
4295                captures,
4296                next_capture: None,
4297                stack: Default::default(),
4298                highlight_maps,
4299            })
4300        }
4301
4302        let diagnostic_endpoints = diagnostics.then(|| Vec::new().into_iter().peekable());
4303        let chunks = text.chunks_in_range(range.clone());
4304
4305        let mut this = BufferChunks {
4306            range,
4307            buffer_snapshot,
4308            chunks,
4309            diagnostic_endpoints,
4310            error_depth: 0,
4311            warning_depth: 0,
4312            information_depth: 0,
4313            hint_depth: 0,
4314            unnecessary_depth: 0,
4315            highlights,
4316        };
4317        this.initialize_diagnostic_endpoints();
4318        this
4319    }
4320
4321    /// Seeks to the given byte offset in the buffer.
4322    pub fn seek(&mut self, range: Range<usize>) {
4323        let old_range = std::mem::replace(&mut self.range, range.clone());
4324        self.chunks.set_range(self.range.clone());
4325        if let Some(highlights) = self.highlights.as_mut() {
4326            if old_range.start <= self.range.start && old_range.end >= self.range.end {
4327                // Reuse existing highlights stack, as the new range is a subrange of the old one.
4328                highlights
4329                    .stack
4330                    .retain(|(end_offset, _)| *end_offset > range.start);
4331                if let Some(capture) = &highlights.next_capture {
4332                    if range.start >= capture.node.start_byte() {
4333                        let next_capture_end = capture.node.end_byte();
4334                        if range.start < next_capture_end {
4335                            highlights.stack.push((
4336                                next_capture_end,
4337                                highlights.highlight_maps[capture.grammar_index].get(capture.index),
4338                            ));
4339                        }
4340                        highlights.next_capture.take();
4341                    }
4342                }
4343            } else if let Some(snapshot) = self.buffer_snapshot {
4344                let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
4345                *highlights = BufferChunkHighlights {
4346                    captures,
4347                    next_capture: None,
4348                    stack: Default::default(),
4349                    highlight_maps,
4350                };
4351            } else {
4352                // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
4353                // Seeking such BufferChunks is not supported.
4354                debug_assert!(false, "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot");
4355            }
4356
4357            highlights.captures.set_byte_range(self.range.clone());
4358            self.initialize_diagnostic_endpoints();
4359        }
4360    }
4361
4362    fn initialize_diagnostic_endpoints(&mut self) {
4363        if let Some(diagnostics) = self.diagnostic_endpoints.as_mut() {
4364            if let Some(buffer) = self.buffer_snapshot {
4365                let mut diagnostic_endpoints = Vec::new();
4366                for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
4367                    diagnostic_endpoints.push(DiagnosticEndpoint {
4368                        offset: entry.range.start,
4369                        is_start: true,
4370                        severity: entry.diagnostic.severity,
4371                        is_unnecessary: entry.diagnostic.is_unnecessary,
4372                    });
4373                    diagnostic_endpoints.push(DiagnosticEndpoint {
4374                        offset: entry.range.end,
4375                        is_start: false,
4376                        severity: entry.diagnostic.severity,
4377                        is_unnecessary: entry.diagnostic.is_unnecessary,
4378                    });
4379                }
4380                diagnostic_endpoints
4381                    .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
4382                *diagnostics = diagnostic_endpoints.into_iter().peekable();
4383                self.hint_depth = 0;
4384                self.error_depth = 0;
4385                self.warning_depth = 0;
4386                self.information_depth = 0;
4387            }
4388        }
4389    }
4390
4391    /// The current byte offset in the buffer.
4392    pub fn offset(&self) -> usize {
4393        self.range.start
4394    }
4395
4396    pub fn range(&self) -> Range<usize> {
4397        self.range.clone()
4398    }
4399
4400    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
4401        let depth = match endpoint.severity {
4402            DiagnosticSeverity::ERROR => &mut self.error_depth,
4403            DiagnosticSeverity::WARNING => &mut self.warning_depth,
4404            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
4405            DiagnosticSeverity::HINT => &mut self.hint_depth,
4406            _ => return,
4407        };
4408        if endpoint.is_start {
4409            *depth += 1;
4410        } else {
4411            *depth -= 1;
4412        }
4413
4414        if endpoint.is_unnecessary {
4415            if endpoint.is_start {
4416                self.unnecessary_depth += 1;
4417            } else {
4418                self.unnecessary_depth -= 1;
4419            }
4420        }
4421    }
4422
4423    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
4424        if self.error_depth > 0 {
4425            Some(DiagnosticSeverity::ERROR)
4426        } else if self.warning_depth > 0 {
4427            Some(DiagnosticSeverity::WARNING)
4428        } else if self.information_depth > 0 {
4429            Some(DiagnosticSeverity::INFORMATION)
4430        } else if self.hint_depth > 0 {
4431            Some(DiagnosticSeverity::HINT)
4432        } else {
4433            None
4434        }
4435    }
4436
4437    fn current_code_is_unnecessary(&self) -> bool {
4438        self.unnecessary_depth > 0
4439    }
4440}
4441
4442impl<'a> Iterator for BufferChunks<'a> {
4443    type Item = Chunk<'a>;
4444
4445    fn next(&mut self) -> Option<Self::Item> {
4446        let mut next_capture_start = usize::MAX;
4447        let mut next_diagnostic_endpoint = usize::MAX;
4448
4449        if let Some(highlights) = self.highlights.as_mut() {
4450            while let Some((parent_capture_end, _)) = highlights.stack.last() {
4451                if *parent_capture_end <= self.range.start {
4452                    highlights.stack.pop();
4453                } else {
4454                    break;
4455                }
4456            }
4457
4458            if highlights.next_capture.is_none() {
4459                highlights.next_capture = highlights.captures.next();
4460            }
4461
4462            while let Some(capture) = highlights.next_capture.as_ref() {
4463                if self.range.start < capture.node.start_byte() {
4464                    next_capture_start = capture.node.start_byte();
4465                    break;
4466                } else {
4467                    let highlight_id =
4468                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
4469                    highlights
4470                        .stack
4471                        .push((capture.node.end_byte(), highlight_id));
4472                    highlights.next_capture = highlights.captures.next();
4473                }
4474            }
4475        }
4476
4477        let mut diagnostic_endpoints = std::mem::take(&mut self.diagnostic_endpoints);
4478        if let Some(diagnostic_endpoints) = diagnostic_endpoints.as_mut() {
4479            while let Some(endpoint) = diagnostic_endpoints.peek().copied() {
4480                if endpoint.offset <= self.range.start {
4481                    self.update_diagnostic_depths(endpoint);
4482                    diagnostic_endpoints.next();
4483                } else {
4484                    next_diagnostic_endpoint = endpoint.offset;
4485                    break;
4486                }
4487            }
4488        }
4489        self.diagnostic_endpoints = diagnostic_endpoints;
4490
4491        if let Some(chunk) = self.chunks.peek() {
4492            let chunk_start = self.range.start;
4493            let mut chunk_end = (self.chunks.offset() + chunk.len())
4494                .min(next_capture_start)
4495                .min(next_diagnostic_endpoint);
4496            let mut highlight_id = None;
4497            if let Some(highlights) = self.highlights.as_ref() {
4498                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
4499                    chunk_end = chunk_end.min(*parent_capture_end);
4500                    highlight_id = Some(*parent_highlight_id);
4501                }
4502            }
4503
4504            let slice =
4505                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
4506            self.range.start = chunk_end;
4507            if self.range.start == self.chunks.offset() + chunk.len() {
4508                self.chunks.next().unwrap();
4509            }
4510
4511            Some(Chunk {
4512                text: slice,
4513                syntax_highlight_id: highlight_id,
4514                diagnostic_severity: self.current_diagnostic_severity(),
4515                is_unnecessary: self.current_code_is_unnecessary(),
4516                ..Default::default()
4517            })
4518        } else {
4519            None
4520        }
4521    }
4522}
4523
4524impl operation_queue::Operation for Operation {
4525    fn lamport_timestamp(&self) -> clock::Lamport {
4526        match self {
4527            Operation::Buffer(_) => {
4528                unreachable!("buffer operations should never be deferred at this layer")
4529            }
4530            Operation::UpdateDiagnostics {
4531                lamport_timestamp, ..
4532            }
4533            | Operation::UpdateSelections {
4534                lamport_timestamp, ..
4535            }
4536            | Operation::UpdateCompletionTriggers {
4537                lamport_timestamp, ..
4538            } => *lamport_timestamp,
4539        }
4540    }
4541}
4542
4543impl Default for Diagnostic {
4544    fn default() -> Self {
4545        Self {
4546            source: Default::default(),
4547            code: None,
4548            severity: DiagnosticSeverity::ERROR,
4549            message: Default::default(),
4550            group_id: 0,
4551            is_primary: false,
4552            is_disk_based: false,
4553            is_unnecessary: false,
4554            data: None,
4555        }
4556    }
4557}
4558
4559impl IndentSize {
4560    /// Returns an [`IndentSize`] representing the given spaces.
4561    pub fn spaces(len: u32) -> Self {
4562        Self {
4563            len,
4564            kind: IndentKind::Space,
4565        }
4566    }
4567
4568    /// Returns an [`IndentSize`] representing a tab.
4569    pub fn tab() -> Self {
4570        Self {
4571            len: 1,
4572            kind: IndentKind::Tab,
4573        }
4574    }
4575
4576    /// An iterator over the characters represented by this [`IndentSize`].
4577    pub fn chars(&self) -> impl Iterator<Item = char> {
4578        iter::repeat(self.char()).take(self.len as usize)
4579    }
4580
4581    /// The character representation of this [`IndentSize`].
4582    pub fn char(&self) -> char {
4583        match self.kind {
4584            IndentKind::Space => ' ',
4585            IndentKind::Tab => '\t',
4586        }
4587    }
4588
4589    /// Consumes the current [`IndentSize`] and returns a new one that has
4590    /// been shrunk or enlarged by the given size along the given direction.
4591    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4592        match direction {
4593            Ordering::Less => {
4594                if self.kind == size.kind && self.len >= size.len {
4595                    self.len -= size.len;
4596                }
4597            }
4598            Ordering::Equal => {}
4599            Ordering::Greater => {
4600                if self.len == 0 {
4601                    self = size;
4602                } else if self.kind == size.kind {
4603                    self.len += size.len;
4604                }
4605            }
4606        }
4607        self
4608    }
4609
4610    pub fn len_with_expanded_tabs(&self, tab_size: NonZeroU32) -> usize {
4611        match self.kind {
4612            IndentKind::Space => self.len as usize,
4613            IndentKind::Tab => self.len as usize * tab_size.get() as usize,
4614        }
4615    }
4616}
4617
4618#[cfg(any(test, feature = "test-support"))]
4619pub struct TestFile {
4620    pub path: Arc<Path>,
4621    pub root_name: String,
4622    pub local_root: Option<PathBuf>,
4623}
4624
4625#[cfg(any(test, feature = "test-support"))]
4626impl File for TestFile {
4627    fn path(&self) -> &Arc<Path> {
4628        &self.path
4629    }
4630
4631    fn full_path(&self, _: &gpui::App) -> PathBuf {
4632        PathBuf::from(&self.root_name).join(self.path.as_ref())
4633    }
4634
4635    fn as_local(&self) -> Option<&dyn LocalFile> {
4636        if self.local_root.is_some() {
4637            Some(self)
4638        } else {
4639            None
4640        }
4641    }
4642
4643    fn disk_state(&self) -> DiskState {
4644        unimplemented!()
4645    }
4646
4647    fn file_name<'a>(&'a self, _: &'a gpui::App) -> &'a std::ffi::OsStr {
4648        self.path().file_name().unwrap_or(self.root_name.as_ref())
4649    }
4650
4651    fn worktree_id(&self, _: &App) -> WorktreeId {
4652        WorktreeId::from_usize(0)
4653    }
4654
4655    fn as_any(&self) -> &dyn std::any::Any {
4656        unimplemented!()
4657    }
4658
4659    fn to_proto(&self, _: &App) -> rpc::proto::File {
4660        unimplemented!()
4661    }
4662
4663    fn is_private(&self) -> bool {
4664        false
4665    }
4666}
4667
4668#[cfg(any(test, feature = "test-support"))]
4669impl LocalFile for TestFile {
4670    fn abs_path(&self, _cx: &App) -> PathBuf {
4671        PathBuf::from(self.local_root.as_ref().unwrap())
4672            .join(&self.root_name)
4673            .join(self.path.as_ref())
4674    }
4675
4676    fn load(&self, _cx: &App) -> Task<Result<String>> {
4677        unimplemented!()
4678    }
4679
4680    fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
4681        unimplemented!()
4682    }
4683}
4684
4685pub(crate) fn contiguous_ranges(
4686    values: impl Iterator<Item = u32>,
4687    max_len: usize,
4688) -> impl Iterator<Item = Range<u32>> {
4689    let mut values = values;
4690    let mut current_range: Option<Range<u32>> = None;
4691    std::iter::from_fn(move || loop {
4692        if let Some(value) = values.next() {
4693            if let Some(range) = &mut current_range {
4694                if value == range.end && range.len() < max_len {
4695                    range.end += 1;
4696                    continue;
4697                }
4698            }
4699
4700            let prev_range = current_range.clone();
4701            current_range = Some(value..(value + 1));
4702            if prev_range.is_some() {
4703                return prev_range;
4704            }
4705        } else {
4706            return current_range.take();
4707        }
4708    })
4709}
4710
4711#[derive(Default, Debug)]
4712pub struct CharClassifier {
4713    scope: Option<LanguageScope>,
4714    for_completion: bool,
4715    ignore_punctuation: bool,
4716}
4717
4718impl CharClassifier {
4719    pub fn new(scope: Option<LanguageScope>) -> Self {
4720        Self {
4721            scope,
4722            for_completion: false,
4723            ignore_punctuation: false,
4724        }
4725    }
4726
4727    pub fn for_completion(self, for_completion: bool) -> Self {
4728        Self {
4729            for_completion,
4730            ..self
4731        }
4732    }
4733
4734    pub fn ignore_punctuation(self, ignore_punctuation: bool) -> Self {
4735        Self {
4736            ignore_punctuation,
4737            ..self
4738        }
4739    }
4740
4741    pub fn is_whitespace(&self, c: char) -> bool {
4742        self.kind(c) == CharKind::Whitespace
4743    }
4744
4745    pub fn is_word(&self, c: char) -> bool {
4746        self.kind(c) == CharKind::Word
4747    }
4748
4749    pub fn is_punctuation(&self, c: char) -> bool {
4750        self.kind(c) == CharKind::Punctuation
4751    }
4752
4753    pub fn kind_with(&self, c: char, ignore_punctuation: bool) -> CharKind {
4754        if c.is_alphanumeric() || c == '_' {
4755            return CharKind::Word;
4756        }
4757
4758        if let Some(scope) = &self.scope {
4759            let characters = if self.for_completion {
4760                scope.completion_query_characters()
4761            } else {
4762                scope.word_characters()
4763            };
4764            if let Some(characters) = characters {
4765                if characters.contains(&c) {
4766                    return CharKind::Word;
4767                }
4768            }
4769        }
4770
4771        if c.is_whitespace() {
4772            return CharKind::Whitespace;
4773        }
4774
4775        if ignore_punctuation {
4776            CharKind::Word
4777        } else {
4778            CharKind::Punctuation
4779        }
4780    }
4781
4782    pub fn kind(&self, c: char) -> CharKind {
4783        self.kind_with(c, self.ignore_punctuation)
4784    }
4785}
4786
4787/// Find all of the ranges of whitespace that occur at the ends of lines
4788/// in the given rope.
4789///
4790/// This could also be done with a regex search, but this implementation
4791/// avoids copying text.
4792pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4793    let mut ranges = Vec::new();
4794
4795    let mut offset = 0;
4796    let mut prev_chunk_trailing_whitespace_range = 0..0;
4797    for chunk in rope.chunks() {
4798        let mut prev_line_trailing_whitespace_range = 0..0;
4799        for (i, line) in chunk.split('\n').enumerate() {
4800            let line_end_offset = offset + line.len();
4801            let trimmed_line_len = line.trim_end_matches([' ', '\t']).len();
4802            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4803
4804            if i == 0 && trimmed_line_len == 0 {
4805                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4806            }
4807            if !prev_line_trailing_whitespace_range.is_empty() {
4808                ranges.push(prev_line_trailing_whitespace_range);
4809            }
4810
4811            offset = line_end_offset + 1;
4812            prev_line_trailing_whitespace_range = trailing_whitespace_range;
4813        }
4814
4815        offset -= 1;
4816        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4817    }
4818
4819    if !prev_chunk_trailing_whitespace_range.is_empty() {
4820        ranges.push(prev_chunk_trailing_whitespace_range);
4821    }
4822
4823    ranges
4824}