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