buffer.rs

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