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