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