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