buffer.rs

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