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, SyntaxMapMatches,
  14        SyntaxSnapshot, ToTreeSitterPoint,
  15    },
  16    LanguageScope, Outline,
  17};
  18use anyhow::{anyhow, Context, Result};
  19pub use clock::ReplicaId;
  20use futures::channel::oneshot;
  21use gpui::{AppContext, EventEmitter, HighlightStyle, ModelContext, Task, TaskLabel};
  22use lazy_static::lazy_static;
  23use lsp::LanguageServerId;
  24use parking_lot::Mutex;
  25use similar::{ChangeTag, TextDiff};
  26use smallvec::SmallVec;
  27use smol::future::yield_now;
  28use std::{
  29    any::Any,
  30    cmp::{self, Ordering},
  31    collections::BTreeMap,
  32    ffi::OsStr,
  33    future::Future,
  34    iter::{self, Iterator, Peekable},
  35    mem,
  36    ops::{Deref, Range},
  37    path::{Path, PathBuf},
  38    str,
  39    sync::Arc,
  40    time::{Duration, Instant, SystemTime},
  41    vec,
  42};
  43use sum_tree::TreeMap;
  44use text::operation_queue::OperationQueue;
  45use text::*;
  46pub use text::{
  47    Anchor, Bias, Buffer as TextBuffer, BufferId, BufferSnapshot as TextBufferSnapshot, Edit,
  48    OffsetRangeExt, OffsetUtf16, Patch, Point, PointUtf16, Rope, Selection, SelectionGoal,
  49    Subscription, TextDimension, TextSummary, ToOffset, ToOffsetUtf16, ToPoint, ToPointUtf16,
  50    Transaction, TransactionId, Unclipped,
  51};
  52use theme::SyntaxTheme;
  53#[cfg(any(test, feature = "test-support"))]
  54use util::RandomCharIter;
  55use util::RangeExt;
  56
  57#[cfg(any(test, feature = "test-support"))]
  58pub use {tree_sitter_rust, tree_sitter_typescript};
  59
  60pub use lsp::DiagnosticSeverity;
  61
  62lazy_static! {
  63    /// A label for the background task spawned by the buffer to compute
  64    /// a diff against the contents of its file.
  65    pub static ref BUFFER_DIFF_TASK: TaskLabel = TaskLabel::new();
  66}
  67
  68/// Indicate whether a [Buffer] has permissions to edit.
  69#[derive(PartialEq, Clone, Copy, Debug)]
  70pub enum Capability {
  71    /// The buffer is a mutable replica.
  72    ReadWrite,
  73    /// The buffer is a read-only replica.
  74    ReadOnly,
  75}
  76
  77/// An in-memory representation of a source code file, including its text,
  78/// syntax trees, git status, and diagnostics.
  79pub struct Buffer {
  80    text: TextBuffer,
  81    diff_base: Option<Rope>,
  82    git_diff: git::diff::BufferDiff,
  83    file: Option<Arc<dyn File>>,
  84    /// The mtime of the file when this buffer was last loaded from
  85    /// or saved to disk.
  86    saved_mtime: Option<SystemTime>,
  87    /// The version vector when this buffer was last loaded from
  88    /// or saved to disk.
  89    saved_version: clock::Global,
  90    transaction_depth: usize,
  91    was_dirty_before_starting_transaction: Option<bool>,
  92    reload_task: Option<Task<Result<()>>>,
  93    language: Option<Arc<Language>>,
  94    autoindent_requests: Vec<Arc<AutoindentRequest>>,
  95    pending_autoindent: Option<Task<()>>,
  96    sync_parse_timeout: Duration,
  97    syntax_map: Mutex<SyntaxMap>,
  98    parsing_in_background: bool,
  99    parse_count: usize,
 100    diagnostics: SmallVec<[(LanguageServerId, DiagnosticSet); 2]>,
 101    remote_selections: TreeMap<ReplicaId, SelectionSet>,
 102    selections_update_count: usize,
 103    diagnostics_update_count: usize,
 104    diagnostics_timestamp: clock::Lamport,
 105    file_update_count: usize,
 106    git_diff_update_count: usize,
 107    completion_triggers: Vec<String>,
 108    completion_triggers_timestamp: clock::Lamport,
 109    deferred_ops: OperationQueue<Operation>,
 110    capability: Capability,
 111    has_conflict: bool,
 112    diff_base_version: usize,
 113}
 114
 115/// An immutable, cheaply cloneable representation of a fixed
 116/// state of a buffer.
 117pub struct BufferSnapshot {
 118    text: text::BufferSnapshot,
 119    git_diff: git::diff::BufferDiff,
 120    pub(crate) syntax: SyntaxSnapshot,
 121    file: Option<Arc<dyn File>>,
 122    diagnostics: SmallVec<[(LanguageServerId, DiagnosticSet); 2]>,
 123    diagnostics_update_count: usize,
 124    file_update_count: usize,
 125    git_diff_update_count: usize,
 126    remote_selections: TreeMap<ReplicaId, SelectionSet>,
 127    selections_update_count: usize,
 128    language: Option<Arc<Language>>,
 129    parse_count: usize,
 130}
 131
 132/// The kind and amount of indentation in a particular line. For now,
 133/// assumes that indentation is all the same character.
 134#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
 135pub struct IndentSize {
 136    /// The number of bytes that comprise the indentation.
 137    pub len: u32,
 138    /// The kind of whitespace used for indentation.
 139    pub kind: IndentKind,
 140}
 141
 142/// A whitespace character that's used for indentation.
 143#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
 144pub enum IndentKind {
 145    /// An ASCII space character.
 146    #[default]
 147    Space,
 148    /// An ASCII tab character.
 149    Tab,
 150}
 151
 152/// The shape of a selection cursor.
 153#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
 154pub enum CursorShape {
 155    /// A vertical bar
 156    #[default]
 157    Bar,
 158    /// A block that surrounds the following character
 159    Block,
 160    /// An underline that runs along the following character
 161    Underscore,
 162    /// A box drawn around the following character
 163    Hollow,
 164}
 165
 166#[derive(Clone, Debug)]
 167struct SelectionSet {
 168    line_mode: bool,
 169    cursor_shape: CursorShape,
 170    selections: Arc<[Selection<Anchor>]>,
 171    lamport_timestamp: clock::Lamport,
 172}
 173
 174/// A diagnostic associated with a certain range of a buffer.
 175#[derive(Clone, Debug, PartialEq, Eq)]
 176pub struct Diagnostic {
 177    /// The name of the service that produced this diagnostic.
 178    pub source: Option<String>,
 179    /// A machine-readable code that identifies this diagnostic.
 180    pub code: Option<String>,
 181    /// Whether this diagnostic is a hint, warning, or error.
 182    pub severity: DiagnosticSeverity,
 183    /// The human-readable message associated with this diagnostic.
 184    pub message: String,
 185    /// An id that identifies the group to which this diagnostic belongs.
 186    ///
 187    /// When a language server produces a diagnostic with
 188    /// one or more associated diagnostics, those diagnostics are all
 189    /// assigned a single group id.
 190    pub group_id: usize,
 191    /// Whether this diagnostic is the primary diagnostic for its group.
 192    ///
 193    /// In a given group, the primary diagnostic is the top-level diagnostic
 194    /// returned by the language server. The non-primary diagnostics are the
 195    /// associated diagnostics.
 196    pub is_primary: bool,
 197    /// Whether this diagnostic is considered to originate from an analysis of
 198    /// files on disk, as opposed to any unsaved buffer contents. This is a
 199    /// property of a given diagnostic source, and is configured for a given
 200    /// language server via the [`LspAdapter::disk_based_diagnostic_sources`](crate::LspAdapter::disk_based_diagnostic_sources) method
 201    /// for the language server.
 202    pub is_disk_based: bool,
 203    /// Whether this diagnostic marks unnecessary code.
 204    pub is_unnecessary: bool,
 205}
 206
 207/// TODO - move this into the `project` crate and make it private.
 208pub async fn prepare_completion_documentation(
 209    documentation: &lsp::Documentation,
 210    language_registry: &Arc<LanguageRegistry>,
 211    language: Option<Arc<Language>>,
 212) -> Documentation {
 213    match documentation {
 214        lsp::Documentation::String(text) => {
 215            if text.lines().count() <= 1 {
 216                Documentation::SingleLine(text.clone())
 217            } else {
 218                Documentation::MultiLinePlainText(text.clone())
 219            }
 220        }
 221
 222        lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
 223            lsp::MarkupKind::PlainText => {
 224                if value.lines().count() <= 1 {
 225                    Documentation::SingleLine(value.clone())
 226                } else {
 227                    Documentation::MultiLinePlainText(value.clone())
 228                }
 229            }
 230
 231            lsp::MarkupKind::Markdown => {
 232                let parsed = parse_markdown(value, language_registry, language).await;
 233                Documentation::MultiLineMarkdown(parsed)
 234            }
 235        },
 236    }
 237}
 238
 239/// Documentation associated with a [`Completion`].
 240#[derive(Clone, Debug)]
 241pub enum Documentation {
 242    /// There is no documentation for this completion.
 243    Undocumented,
 244    /// A single line of documentation.
 245    SingleLine(String),
 246    /// Multiple lines of plain text documentation.
 247    MultiLinePlainText(String),
 248    /// Markdown documentation.
 249    MultiLineMarkdown(ParsedMarkdown),
 250}
 251
 252/// An operation used to synchronize this buffer with its other replicas.
 253#[derive(Clone, Debug, PartialEq)]
 254pub enum Operation {
 255    /// A text operation.
 256    Buffer(text::Operation),
 257
 258    /// An update to the buffer's diagnostics.
 259    UpdateDiagnostics {
 260        /// The id of the language server that produced the new diagnostics.
 261        server_id: LanguageServerId,
 262        /// The diagnostics.
 263        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
 264        /// The buffer's lamport timestamp.
 265        lamport_timestamp: clock::Lamport,
 266    },
 267
 268    /// An update to the most recent selections in this buffer.
 269    UpdateSelections {
 270        /// The selections.
 271        selections: Arc<[Selection<Anchor>]>,
 272        /// The buffer's lamport timestamp.
 273        lamport_timestamp: clock::Lamport,
 274        /// Whether the selections are in 'line mode'.
 275        line_mode: bool,
 276        /// The [`CursorShape`] associated with these selections.
 277        cursor_shape: CursorShape,
 278    },
 279
 280    /// An update to the characters that should trigger autocompletion
 281    /// for this buffer.
 282    UpdateCompletionTriggers {
 283        /// The characters that trigger autocompletion.
 284        triggers: Vec<String>,
 285        /// The buffer's lamport timestamp.
 286        lamport_timestamp: clock::Lamport,
 287    },
 288}
 289
 290/// An event that occurs in a buffer.
 291#[derive(Clone, Debug, PartialEq)]
 292pub enum Event {
 293    /// The buffer was changed in a way that must be
 294    /// propagated to its other replicas.
 295    Operation(Operation),
 296    /// The buffer was edited.
 297    Edited,
 298    /// The buffer's `dirty` bit changed.
 299    DirtyChanged,
 300    /// The buffer was saved.
 301    Saved,
 302    /// The buffer's file was changed on disk.
 303    FileHandleChanged,
 304    /// The buffer was reloaded.
 305    Reloaded,
 306    /// The buffer's diff_base changed.
 307    DiffBaseChanged,
 308    /// Buffer's excerpts for a certain diff base were recalculated.
 309    DiffUpdated,
 310    /// The buffer's language was changed.
 311    LanguageChanged,
 312    /// The buffer's syntax trees were updated.
 313    Reparsed,
 314    /// The buffer's diagnostics were updated.
 315    DiagnosticsUpdated,
 316    /// The buffer gained or lost editing capabilities.
 317    CapabilityChanged,
 318    /// The buffer was explicitly requested to close.
 319    Closed,
 320}
 321
 322/// The file associated with a buffer.
 323pub trait File: Send + Sync {
 324    /// Returns the [`LocalFile`] associated with this file, if the
 325    /// file is local.
 326    fn as_local(&self) -> Option<&dyn LocalFile>;
 327
 328    /// Returns whether this file is local.
 329    fn is_local(&self) -> bool {
 330        self.as_local().is_some()
 331    }
 332
 333    /// Returns the file's mtime.
 334    fn mtime(&self) -> Option<SystemTime>;
 335
 336    /// Returns the path of this file relative to the worktree's root directory.
 337    fn path(&self) -> &Arc<Path>;
 338
 339    /// Returns the path of this file relative to the worktree's parent directory (this means it
 340    /// includes the name of the worktree's root folder).
 341    fn full_path(&self, cx: &AppContext) -> PathBuf;
 342
 343    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 344    /// of its worktree, then this method will return the name of the worktree itself.
 345    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr;
 346
 347    /// Returns the id of the worktree to which this file belongs.
 348    ///
 349    /// This is needed for looking up project-specific settings.
 350    fn worktree_id(&self) -> usize;
 351
 352    /// Returns whether the file has been deleted.
 353    fn is_deleted(&self) -> bool;
 354
 355    /// Returns whether the file existed on disk at one point
 356    fn is_created(&self) -> bool {
 357        self.mtime().is_some()
 358    }
 359
 360    /// Converts this file into an [`Any`] trait object.
 361    fn as_any(&self) -> &dyn Any;
 362
 363    /// Converts this file into a protobuf message.
 364    fn to_proto(&self) -> rpc::proto::File;
 365
 366    /// Return whether Zed considers this to be a private file.
 367    fn is_private(&self) -> bool;
 368}
 369
 370/// The file associated with a buffer, in the case where the file is on the local disk.
 371pub trait LocalFile: File {
 372    /// Returns the absolute path of this file.
 373    fn abs_path(&self, cx: &AppContext) -> PathBuf;
 374
 375    /// Loads the file's contents from disk.
 376    fn load(&self, cx: &AppContext) -> Task<Result<String>>;
 377
 378    /// Called when the buffer is reloaded from disk.
 379    fn buffer_reloaded(
 380        &self,
 381        buffer_id: BufferId,
 382        version: &clock::Global,
 383        line_ending: LineEnding,
 384        mtime: Option<SystemTime>,
 385        cx: &mut AppContext,
 386    );
 387
 388    /// Returns true if the file should not be shared with collaborators.
 389    fn is_private(&self, _: &AppContext) -> bool {
 390        false
 391    }
 392}
 393
 394/// The auto-indent behavior associated with an editing operation.
 395/// For some editing operations, each affected line of text has its
 396/// indentation recomputed. For other operations, the entire block
 397/// of edited text is adjusted uniformly.
 398#[derive(Clone, Debug)]
 399pub enum AutoindentMode {
 400    /// Indent each line of inserted text.
 401    EachLine,
 402    /// Apply the same indentation adjustment to all of the lines
 403    /// in a given insertion.
 404    Block {
 405        /// The original indentation level of the first line of each
 406        /// insertion, if it has been copied.
 407        original_indent_columns: Vec<u32>,
 408    },
 409}
 410
 411#[derive(Clone)]
 412struct AutoindentRequest {
 413    before_edit: BufferSnapshot,
 414    entries: Vec<AutoindentRequestEntry>,
 415    is_block_mode: bool,
 416}
 417
 418#[derive(Clone)]
 419struct AutoindentRequestEntry {
 420    /// A range of the buffer whose indentation should be adjusted.
 421    range: Range<Anchor>,
 422    /// Whether or not these lines should be considered brand new, for the
 423    /// purpose of auto-indent. When text is not new, its indentation will
 424    /// only be adjusted if the suggested indentation level has *changed*
 425    /// since the edit was made.
 426    first_line_is_new: bool,
 427    indent_size: IndentSize,
 428    original_indent_column: Option<u32>,
 429}
 430
 431#[derive(Debug)]
 432struct IndentSuggestion {
 433    basis_row: u32,
 434    delta: Ordering,
 435    within_error: bool,
 436}
 437
 438struct BufferChunkHighlights<'a> {
 439    captures: SyntaxMapCaptures<'a>,
 440    next_capture: Option<SyntaxMapCapture<'a>>,
 441    stack: Vec<(usize, HighlightId)>,
 442    highlight_maps: Vec<HighlightMap>,
 443}
 444
 445/// An iterator that yields chunks of a buffer's text, along with their
 446/// syntax highlights and diagnostic status.
 447pub struct BufferChunks<'a> {
 448    range: Range<usize>,
 449    chunks: text::Chunks<'a>,
 450    diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
 451    error_depth: usize,
 452    warning_depth: usize,
 453    information_depth: usize,
 454    hint_depth: usize,
 455    unnecessary_depth: usize,
 456    highlights: Option<BufferChunkHighlights<'a>>,
 457}
 458
 459/// A chunk of a buffer's text, along with its syntax highlight and
 460/// diagnostic status.
 461#[derive(Clone, Copy, Debug, Default)]
 462pub struct Chunk<'a> {
 463    /// The text of the chunk.
 464    pub text: &'a str,
 465    /// The syntax highlighting style of the chunk.
 466    pub syntax_highlight_id: Option<HighlightId>,
 467    /// The highlight style that has been applied to this chunk in
 468    /// the editor.
 469    pub highlight_style: Option<HighlightStyle>,
 470    /// The severity of diagnostic associated with this chunk, if any.
 471    pub diagnostic_severity: Option<DiagnosticSeverity>,
 472    /// Whether this chunk of text is marked as unnecessary.
 473    pub is_unnecessary: bool,
 474    /// Whether this chunk of text was originally a tab character.
 475    pub is_tab: bool,
 476}
 477
 478/// A set of edits to a given version of a buffer, computed asynchronously.
 479pub struct Diff {
 480    pub(crate) base_version: clock::Global,
 481    line_ending: LineEnding,
 482    edits: Vec<(Range<usize>, Arc<str>)>,
 483}
 484
 485#[derive(Clone, Copy)]
 486pub(crate) struct DiagnosticEndpoint {
 487    offset: usize,
 488    is_start: bool,
 489    severity: DiagnosticSeverity,
 490    is_unnecessary: bool,
 491}
 492
 493/// A class of characters, used for characterizing a run of text.
 494#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug)]
 495pub enum CharKind {
 496    /// Whitespace.
 497    Whitespace,
 498    /// Punctuation.
 499    Punctuation,
 500    /// Word.
 501    Word,
 502}
 503
 504impl Buffer {
 505    /// Create a new buffer with the given base text.
 506    pub fn local<T: Into<String>>(base_text: T, cx: &mut ModelContext<Self>) -> Self {
 507        Self::build(
 508            TextBuffer::new(0, cx.entity_id().as_non_zero_u64().into(), base_text.into()),
 509            None,
 510            None,
 511            Capability::ReadWrite,
 512        )
 513    }
 514
 515    /// Create a new buffer with the given base text that has proper line endings and other normalization applied.
 516    pub fn local_normalized(
 517        base_text_normalized: Rope,
 518        line_ending: LineEnding,
 519        cx: &mut ModelContext<Self>,
 520    ) -> Self {
 521        Self::build(
 522            TextBuffer::new_normalized(
 523                0,
 524                cx.entity_id().as_non_zero_u64().into(),
 525                line_ending,
 526                base_text_normalized,
 527            ),
 528            None,
 529            None,
 530            Capability::ReadWrite,
 531        )
 532    }
 533
 534    /// Create a new buffer that is a replica of a remote buffer.
 535    pub fn remote(
 536        remote_id: BufferId,
 537        replica_id: ReplicaId,
 538        capability: Capability,
 539        base_text: impl Into<String>,
 540    ) -> Self {
 541        Self::build(
 542            TextBuffer::new(replica_id, remote_id, base_text.into()),
 543            None,
 544            None,
 545            capability,
 546        )
 547    }
 548
 549    /// Create a new buffer that is a replica of a remote buffer, populating its
 550    /// state from the given protobuf message.
 551    pub fn from_proto(
 552        replica_id: ReplicaId,
 553        capability: Capability,
 554        message: proto::BufferState,
 555        file: Option<Arc<dyn File>>,
 556    ) -> Result<Self> {
 557        let buffer_id = BufferId::new(message.id)
 558            .with_context(|| anyhow!("Could not deserialize buffer_id"))?;
 559        let buffer = TextBuffer::new(replica_id, buffer_id, message.base_text);
 560        let mut this = Self::build(
 561            buffer,
 562            message.diff_base.map(|text| text.into()),
 563            file,
 564            capability,
 565        );
 566        this.text.set_line_ending(proto::deserialize_line_ending(
 567            rpc::proto::LineEnding::from_i32(message.line_ending)
 568                .ok_or_else(|| anyhow!("missing line_ending"))?,
 569        ));
 570        this.saved_version = proto::deserialize_version(&message.saved_version);
 571        this.saved_mtime = message.saved_mtime.map(|time| time.into());
 572        Ok(this)
 573    }
 574
 575    /// Serialize the buffer's state to a protobuf message.
 576    pub fn to_proto(&self) -> proto::BufferState {
 577        proto::BufferState {
 578            id: self.remote_id().into(),
 579            file: self.file.as_ref().map(|f| f.to_proto()),
 580            base_text: self.base_text().to_string(),
 581            diff_base: self.diff_base.as_ref().map(|h| h.to_string()),
 582            line_ending: proto::serialize_line_ending(self.line_ending()) as i32,
 583            saved_version: proto::serialize_version(&self.saved_version),
 584            saved_mtime: self.saved_mtime.map(|time| time.into()),
 585        }
 586    }
 587
 588    /// Serialize as protobufs all of the changes to the buffer since the given version.
 589    pub fn serialize_ops(
 590        &self,
 591        since: Option<clock::Global>,
 592        cx: &AppContext,
 593    ) -> Task<Vec<proto::Operation>> {
 594        let mut operations = Vec::new();
 595        operations.extend(self.deferred_ops.iter().map(proto::serialize_operation));
 596
 597        operations.extend(self.remote_selections.iter().map(|(_, set)| {
 598            proto::serialize_operation(&Operation::UpdateSelections {
 599                selections: set.selections.clone(),
 600                lamport_timestamp: set.lamport_timestamp,
 601                line_mode: set.line_mode,
 602                cursor_shape: set.cursor_shape,
 603            })
 604        }));
 605
 606        for (server_id, diagnostics) in &self.diagnostics {
 607            operations.push(proto::serialize_operation(&Operation::UpdateDiagnostics {
 608                lamport_timestamp: self.diagnostics_timestamp,
 609                server_id: *server_id,
 610                diagnostics: diagnostics.iter().cloned().collect(),
 611            }));
 612        }
 613
 614        operations.push(proto::serialize_operation(
 615            &Operation::UpdateCompletionTriggers {
 616                triggers: self.completion_triggers.clone(),
 617                lamport_timestamp: self.completion_triggers_timestamp,
 618            },
 619        ));
 620
 621        let text_operations = self.text.operations().clone();
 622        cx.background_executor().spawn(async move {
 623            let since = since.unwrap_or_default();
 624            operations.extend(
 625                text_operations
 626                    .iter()
 627                    .filter(|(_, op)| !since.observed(op.timestamp()))
 628                    .map(|(_, op)| proto::serialize_operation(&Operation::Buffer(op.clone()))),
 629            );
 630            operations.sort_unstable_by_key(proto::lamport_timestamp_for_operation);
 631            operations
 632        })
 633    }
 634
 635    /// Assign a language to the buffer, returning the buffer.
 636    pub fn with_language(mut self, language: Arc<Language>, cx: &mut ModelContext<Self>) -> Self {
 637        self.set_language(Some(language), cx);
 638        self
 639    }
 640
 641    /// Returns the [Capability] of this buffer.
 642    pub fn capability(&self) -> Capability {
 643        self.capability
 644    }
 645
 646    /// Whether this buffer can only be read.
 647    pub fn read_only(&self) -> bool {
 648        self.capability == Capability::ReadOnly
 649    }
 650
 651    /// Builds a [Buffer] with the given underlying [TextBuffer], diff base, [File] and [Capability].
 652    pub fn build(
 653        buffer: TextBuffer,
 654        diff_base: Option<Rope>,
 655        file: Option<Arc<dyn File>>,
 656        capability: Capability,
 657    ) -> Self {
 658        let saved_mtime = file.as_ref().and_then(|file| file.mtime());
 659
 660        Self {
 661            saved_mtime,
 662            saved_version: buffer.version(),
 663            reload_task: None,
 664            transaction_depth: 0,
 665            was_dirty_before_starting_transaction: None,
 666            text: buffer,
 667            diff_base,
 668            diff_base_version: 0,
 669            git_diff: git::diff::BufferDiff::new(),
 670            file,
 671            capability,
 672            syntax_map: Mutex::new(SyntaxMap::new()),
 673            parsing_in_background: false,
 674            parse_count: 0,
 675            sync_parse_timeout: Duration::from_millis(1),
 676            autoindent_requests: Default::default(),
 677            pending_autoindent: Default::default(),
 678            language: None,
 679            remote_selections: Default::default(),
 680            selections_update_count: 0,
 681            diagnostics: Default::default(),
 682            diagnostics_update_count: 0,
 683            diagnostics_timestamp: Default::default(),
 684            file_update_count: 0,
 685            git_diff_update_count: 0,
 686            completion_triggers: Default::default(),
 687            completion_triggers_timestamp: Default::default(),
 688            deferred_ops: OperationQueue::new(),
 689            has_conflict: false,
 690        }
 691    }
 692
 693    /// Retrieve a snapshot of the buffer's current state. This is computationally
 694    /// cheap, and allows reading from the buffer on a background thread.
 695    pub fn snapshot(&self) -> BufferSnapshot {
 696        let text = self.text.snapshot();
 697        let mut syntax_map = self.syntax_map.lock();
 698        syntax_map.interpolate(&text);
 699        let syntax = syntax_map.snapshot();
 700
 701        BufferSnapshot {
 702            text,
 703            syntax,
 704            git_diff: self.git_diff.clone(),
 705            file: self.file.clone(),
 706            remote_selections: self.remote_selections.clone(),
 707            diagnostics: self.diagnostics.clone(),
 708            diagnostics_update_count: self.diagnostics_update_count,
 709            file_update_count: self.file_update_count,
 710            git_diff_update_count: self.git_diff_update_count,
 711            language: self.language.clone(),
 712            parse_count: self.parse_count,
 713            selections_update_count: self.selections_update_count,
 714        }
 715    }
 716
 717    #[cfg(test)]
 718    pub(crate) fn as_text_snapshot(&self) -> &text::BufferSnapshot {
 719        &self.text
 720    }
 721
 722    /// Retrieve a snapshot of the buffer's raw text, without any
 723    /// language-related state like the syntax tree or diagnostics.
 724    pub fn text_snapshot(&self) -> text::BufferSnapshot {
 725        self.text.snapshot()
 726    }
 727
 728    /// The file associated with the buffer, if any.
 729    pub fn file(&self) -> Option<&Arc<dyn File>> {
 730        self.file.as_ref()
 731    }
 732
 733    /// The version of the buffer that was last saved or reloaded from disk.
 734    pub fn saved_version(&self) -> &clock::Global {
 735        &self.saved_version
 736    }
 737
 738    /// The mtime of the buffer's file when the buffer was last saved or reloaded from disk.
 739    pub fn saved_mtime(&self) -> Option<SystemTime> {
 740        self.saved_mtime
 741    }
 742
 743    /// Assign a language to the buffer.
 744    pub fn set_language(&mut self, language: Option<Arc<Language>>, cx: &mut ModelContext<Self>) {
 745        self.parse_count += 1;
 746        self.syntax_map.lock().clear();
 747        self.language = language;
 748        self.reparse(cx);
 749        cx.emit(Event::LanguageChanged);
 750    }
 751
 752    /// Assign a language registry to the buffer. This allows the buffer to retrieve
 753    /// other languages if parts of the buffer are written in different languages.
 754    pub fn set_language_registry(&mut self, language_registry: Arc<LanguageRegistry>) {
 755        self.syntax_map
 756            .lock()
 757            .set_language_registry(language_registry);
 758    }
 759
 760    /// Assign the buffer a new [Capability].
 761    pub fn set_capability(&mut self, capability: Capability, cx: &mut ModelContext<Self>) {
 762        self.capability = capability;
 763        cx.emit(Event::CapabilityChanged)
 764    }
 765
 766    /// This method is called to signal that the buffer has been saved.
 767    pub fn did_save(
 768        &mut self,
 769        version: clock::Global,
 770        mtime: Option<SystemTime>,
 771        cx: &mut ModelContext<Self>,
 772    ) {
 773        self.saved_version = version;
 774        self.has_conflict = false;
 775        self.saved_mtime = mtime;
 776        cx.emit(Event::Saved);
 777        cx.notify();
 778    }
 779
 780    /// Reloads the contents of the buffer from disk.
 781    pub fn reload(
 782        &mut self,
 783        cx: &mut ModelContext<Self>,
 784    ) -> oneshot::Receiver<Option<Transaction>> {
 785        let (tx, rx) = futures::channel::oneshot::channel();
 786        let prev_version = self.text.version();
 787        self.reload_task = Some(cx.spawn(|this, mut cx| async move {
 788            let Some((new_mtime, new_text)) = this.update(&mut cx, |this, cx| {
 789                let file = this.file.as_ref()?.as_local()?;
 790                Some((file.mtime(), file.load(cx)))
 791            })?
 792            else {
 793                return Ok(());
 794            };
 795
 796            let new_text = new_text.await?;
 797            let diff = this
 798                .update(&mut cx, |this, cx| this.diff(new_text.clone(), cx))?
 799                .await;
 800            this.update(&mut cx, |this, cx| {
 801                if this.version() == diff.base_version {
 802                    this.finalize_last_transaction();
 803                    this.apply_diff(diff, cx);
 804                    tx.send(this.finalize_last_transaction().cloned()).ok();
 805                    this.has_conflict = false;
 806                    this.did_reload(this.version(), this.line_ending(), new_mtime, cx);
 807                } else {
 808                    if !diff.edits.is_empty()
 809                        || this
 810                            .edits_since::<usize>(&diff.base_version)
 811                            .next()
 812                            .is_some()
 813                    {
 814                        this.has_conflict = true;
 815                    }
 816
 817                    this.did_reload(prev_version, this.line_ending(), this.saved_mtime, cx);
 818                }
 819
 820                this.reload_task.take();
 821            })
 822        }));
 823        rx
 824    }
 825
 826    /// This method is called to signal that the buffer has been reloaded.
 827    pub fn did_reload(
 828        &mut self,
 829        version: clock::Global,
 830        line_ending: LineEnding,
 831        mtime: Option<SystemTime>,
 832        cx: &mut ModelContext<Self>,
 833    ) {
 834        self.saved_version = version;
 835        self.text.set_line_ending(line_ending);
 836        self.saved_mtime = mtime;
 837        if let Some(file) = self.file.as_ref().and_then(|f| f.as_local()) {
 838            file.buffer_reloaded(
 839                self.remote_id(),
 840                &self.saved_version,
 841                self.line_ending(),
 842                self.saved_mtime,
 843                cx,
 844            );
 845        }
 846        cx.emit(Event::Reloaded);
 847        cx.notify();
 848    }
 849
 850    /// Updates the [File] backing this buffer. This should be called when
 851    /// the file has changed or has been deleted.
 852    pub fn file_updated(&mut self, new_file: Arc<dyn File>, cx: &mut ModelContext<Self>) {
 853        let mut file_changed = false;
 854
 855        if let Some(old_file) = self.file.as_ref() {
 856            if new_file.path() != old_file.path() {
 857                file_changed = true;
 858            }
 859
 860            if new_file.is_deleted() {
 861                if !old_file.is_deleted() {
 862                    file_changed = true;
 863                    if !self.is_dirty() {
 864                        cx.emit(Event::DirtyChanged);
 865                    }
 866                }
 867            } else {
 868                let new_mtime = new_file.mtime();
 869                if new_mtime != old_file.mtime() {
 870                    file_changed = true;
 871
 872                    if !self.is_dirty() {
 873                        self.reload(cx).close();
 874                    }
 875                }
 876            }
 877        } else {
 878            file_changed = true;
 879        };
 880
 881        self.file = Some(new_file);
 882        if file_changed {
 883            self.file_update_count += 1;
 884            cx.emit(Event::FileHandleChanged);
 885            cx.notify();
 886        }
 887    }
 888
 889    /// Returns the current diff base, see [Buffer::set_diff_base].
 890    pub fn diff_base(&self) -> Option<&Rope> {
 891        self.diff_base.as_ref()
 892    }
 893
 894    /// Sets the text that will be used to compute a Git diff
 895    /// against the buffer text.
 896    pub fn set_diff_base(&mut self, diff_base: Option<Rope>, cx: &mut ModelContext<Self>) {
 897        self.diff_base = diff_base;
 898        self.diff_base_version += 1;
 899        if let Some(recalc_task) = self.git_diff_recalc(cx) {
 900            cx.spawn(|buffer, mut cx| async move {
 901                recalc_task.await;
 902                buffer
 903                    .update(&mut cx, |_, cx| {
 904                        cx.emit(Event::DiffBaseChanged);
 905                    })
 906                    .ok();
 907            })
 908            .detach();
 909        }
 910    }
 911
 912    /// Returns a number, unique per diff base set to the buffer.
 913    pub fn diff_base_version(&self) -> usize {
 914        self.diff_base_version
 915    }
 916
 917    /// Recomputes the Git diff status.
 918    pub fn git_diff_recalc(&mut self, cx: &mut ModelContext<Self>) -> Option<Task<()>> {
 919        let diff_base = self.diff_base.clone()?; // TODO: Make this an Arc
 920        let snapshot = self.snapshot();
 921
 922        let mut diff = self.git_diff.clone();
 923        let diff = cx.background_executor().spawn(async move {
 924            diff.update(&diff_base, &snapshot).await;
 925            diff
 926        });
 927
 928        Some(cx.spawn(|this, mut cx| async move {
 929            let buffer_diff = diff.await;
 930            this.update(&mut cx, |this, cx| {
 931                this.git_diff = buffer_diff;
 932                this.git_diff_update_count += 1;
 933                cx.emit(Event::DiffUpdated);
 934            })
 935            .ok();
 936        }))
 937    }
 938
 939    /// Returns the primary [Language] assigned to this [Buffer].
 940    pub fn language(&self) -> Option<&Arc<Language>> {
 941        self.language.as_ref()
 942    }
 943
 944    /// Returns the [Language] at the given location.
 945    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<Arc<Language>> {
 946        let offset = position.to_offset(self);
 947        self.syntax_map
 948            .lock()
 949            .layers_for_range(offset..offset, &self.text)
 950            .last()
 951            .map(|info| info.language.clone())
 952            .or_else(|| self.language.clone())
 953    }
 954
 955    /// The number of times the buffer was parsed.
 956    pub fn parse_count(&self) -> usize {
 957        self.parse_count
 958    }
 959
 960    /// The number of times selections were updated.
 961    pub fn selections_update_count(&self) -> usize {
 962        self.selections_update_count
 963    }
 964
 965    /// The number of times diagnostics were updated.
 966    pub fn diagnostics_update_count(&self) -> usize {
 967        self.diagnostics_update_count
 968    }
 969
 970    /// The number of times the underlying file was updated.
 971    pub fn file_update_count(&self) -> usize {
 972        self.file_update_count
 973    }
 974
 975    /// The number of times the git diff status was updated.
 976    pub fn git_diff_update_count(&self) -> usize {
 977        self.git_diff_update_count
 978    }
 979
 980    /// Whether the buffer is being parsed in the background.
 981    #[cfg(any(test, feature = "test-support"))]
 982    pub fn is_parsing(&self) -> bool {
 983        self.parsing_in_background
 984    }
 985
 986    /// Indicates whether the buffer contains any regions that may be
 987    /// written in a language that hasn't been loaded yet.
 988    pub fn contains_unknown_injections(&self) -> bool {
 989        self.syntax_map.lock().contains_unknown_injections()
 990    }
 991
 992    #[cfg(test)]
 993    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
 994        self.sync_parse_timeout = timeout;
 995    }
 996
 997    /// Called after an edit to synchronize the buffer's main parse tree with
 998    /// the buffer's new underlying state.
 999    ///
1000    /// Locks the syntax map and interpolates the edits since the last reparse
1001    /// into the foreground syntax tree.
1002    ///
1003    /// Then takes a stable snapshot of the syntax map before unlocking it.
1004    /// The snapshot with the interpolated edits is sent to a background thread,
1005    /// where we ask Tree-sitter to perform an incremental parse.
1006    ///
1007    /// Meanwhile, in the foreground, we block the main thread for up to 1ms
1008    /// waiting on the parse to complete. As soon as it completes, we proceed
1009    /// synchronously, unless a 1ms timeout elapses.
1010    ///
1011    /// If we time out waiting on the parse, we spawn a second task waiting
1012    /// until the parse does complete and return with the interpolated tree still
1013    /// in the foreground. When the background parse completes, call back into
1014    /// the main thread and assign the foreground parse state.
1015    ///
1016    /// If the buffer or grammar changed since the start of the background parse,
1017    /// initiate an additional reparse recursively. To avoid concurrent parses
1018    /// for the same buffer, we only initiate a new parse if we are not already
1019    /// parsing in the background.
1020    pub fn reparse(&mut self, cx: &mut ModelContext<Self>) {
1021        if self.parsing_in_background {
1022            return;
1023        }
1024        let language = if let Some(language) = self.language.clone() {
1025            language
1026        } else {
1027            return;
1028        };
1029
1030        let text = self.text_snapshot();
1031        let parsed_version = self.version();
1032
1033        let mut syntax_map = self.syntax_map.lock();
1034        syntax_map.interpolate(&text);
1035        let language_registry = syntax_map.language_registry();
1036        let mut syntax_snapshot = syntax_map.snapshot();
1037        drop(syntax_map);
1038
1039        let parse_task = cx.background_executor().spawn({
1040            let language = language.clone();
1041            let language_registry = language_registry.clone();
1042            async move {
1043                syntax_snapshot.reparse(&text, language_registry, language);
1044                syntax_snapshot
1045            }
1046        });
1047
1048        match cx
1049            .background_executor()
1050            .block_with_timeout(self.sync_parse_timeout, parse_task)
1051        {
1052            Ok(new_syntax_snapshot) => {
1053                self.did_finish_parsing(new_syntax_snapshot, cx);
1054                return;
1055            }
1056            Err(parse_task) => {
1057                self.parsing_in_background = true;
1058                cx.spawn(move |this, mut cx| async move {
1059                    let new_syntax_map = parse_task.await;
1060                    this.update(&mut cx, move |this, cx| {
1061                        let grammar_changed =
1062                            this.language.as_ref().map_or(true, |current_language| {
1063                                !Arc::ptr_eq(&language, current_language)
1064                            });
1065                        let language_registry_changed = new_syntax_map
1066                            .contains_unknown_injections()
1067                            && language_registry.map_or(false, |registry| {
1068                                registry.version() != new_syntax_map.language_registry_version()
1069                            });
1070                        let parse_again = language_registry_changed
1071                            || grammar_changed
1072                            || this.version.changed_since(&parsed_version);
1073                        this.did_finish_parsing(new_syntax_map, cx);
1074                        this.parsing_in_background = false;
1075                        if parse_again {
1076                            this.reparse(cx);
1077                        }
1078                    })
1079                    .ok();
1080                })
1081                .detach();
1082            }
1083        }
1084    }
1085
1086    fn did_finish_parsing(&mut self, syntax_snapshot: SyntaxSnapshot, cx: &mut ModelContext<Self>) {
1087        self.parse_count += 1;
1088        self.syntax_map.lock().did_parse(syntax_snapshot);
1089        self.request_autoindent(cx);
1090        cx.emit(Event::Reparsed);
1091        cx.notify();
1092    }
1093
1094    /// Assign to the buffer a set of diagnostics created by a given language server.
1095    pub fn update_diagnostics(
1096        &mut self,
1097        server_id: LanguageServerId,
1098        diagnostics: DiagnosticSet,
1099        cx: &mut ModelContext<Self>,
1100    ) {
1101        let lamport_timestamp = self.text.lamport_clock.tick();
1102        let op = Operation::UpdateDiagnostics {
1103            server_id,
1104            diagnostics: diagnostics.iter().cloned().collect(),
1105            lamport_timestamp,
1106        };
1107        self.apply_diagnostic_update(server_id, diagnostics, lamport_timestamp, cx);
1108        self.send_operation(op, cx);
1109    }
1110
1111    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
1112        if let Some(indent_sizes) = self.compute_autoindents() {
1113            let indent_sizes = cx.background_executor().spawn(indent_sizes);
1114            match cx
1115                .background_executor()
1116                .block_with_timeout(Duration::from_micros(500), indent_sizes)
1117            {
1118                Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
1119                Err(indent_sizes) => {
1120                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
1121                        let indent_sizes = indent_sizes.await;
1122                        this.update(&mut cx, |this, cx| {
1123                            this.apply_autoindents(indent_sizes, cx);
1124                        })
1125                        .ok();
1126                    }));
1127                }
1128            }
1129        } else {
1130            self.autoindent_requests.clear();
1131        }
1132    }
1133
1134    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>>> {
1135        let max_rows_between_yields = 100;
1136        let snapshot = self.snapshot();
1137        if snapshot.syntax.is_empty() || self.autoindent_requests.is_empty() {
1138            return None;
1139        }
1140
1141        let autoindent_requests = self.autoindent_requests.clone();
1142        Some(async move {
1143            let mut indent_sizes = BTreeMap::new();
1144            for request in autoindent_requests {
1145                // Resolve each edited range to its row in the current buffer and in the
1146                // buffer before this batch of edits.
1147                let mut row_ranges = Vec::new();
1148                let mut old_to_new_rows = BTreeMap::new();
1149                let mut language_indent_sizes_by_new_row = Vec::new();
1150                for entry in &request.entries {
1151                    let position = entry.range.start;
1152                    let new_row = position.to_point(&snapshot).row;
1153                    let new_end_row = entry.range.end.to_point(&snapshot).row + 1;
1154                    language_indent_sizes_by_new_row.push((new_row, entry.indent_size));
1155
1156                    if !entry.first_line_is_new {
1157                        let old_row = position.to_point(&request.before_edit).row;
1158                        old_to_new_rows.insert(old_row, new_row);
1159                    }
1160                    row_ranges.push((new_row..new_end_row, entry.original_indent_column));
1161                }
1162
1163                // Build a map containing the suggested indentation for each of the edited lines
1164                // with respect to the state of the buffer before these edits. This map is keyed
1165                // by the rows for these lines in the current state of the buffer.
1166                let mut old_suggestions = BTreeMap::<u32, (IndentSize, bool)>::default();
1167                let old_edited_ranges =
1168                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
1169                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1170                let mut language_indent_size = IndentSize::default();
1171                for old_edited_range in old_edited_ranges {
1172                    let suggestions = request
1173                        .before_edit
1174                        .suggest_autoindents(old_edited_range.clone())
1175                        .into_iter()
1176                        .flatten();
1177                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
1178                        if let Some(suggestion) = suggestion {
1179                            let new_row = *old_to_new_rows.get(&old_row).unwrap();
1180
1181                            // Find the indent size based on the language for this row.
1182                            while let Some((row, size)) = language_indent_sizes.peek() {
1183                                if *row > new_row {
1184                                    break;
1185                                }
1186                                language_indent_size = *size;
1187                                language_indent_sizes.next();
1188                            }
1189
1190                            let suggested_indent = old_to_new_rows
1191                                .get(&suggestion.basis_row)
1192                                .and_then(|from_row| {
1193                                    Some(old_suggestions.get(from_row).copied()?.0)
1194                                })
1195                                .unwrap_or_else(|| {
1196                                    request
1197                                        .before_edit
1198                                        .indent_size_for_line(suggestion.basis_row)
1199                                })
1200                                .with_delta(suggestion.delta, language_indent_size);
1201                            old_suggestions
1202                                .insert(new_row, (suggested_indent, suggestion.within_error));
1203                        }
1204                    }
1205                    yield_now().await;
1206                }
1207
1208                // In block mode, only compute indentation suggestions for the first line
1209                // of each insertion. Otherwise, compute suggestions for every inserted line.
1210                let new_edited_row_ranges = contiguous_ranges(
1211                    row_ranges.iter().flat_map(|(range, _)| {
1212                        if request.is_block_mode {
1213                            range.start..range.start + 1
1214                        } else {
1215                            range.clone()
1216                        }
1217                    }),
1218                    max_rows_between_yields,
1219                );
1220
1221                // Compute new suggestions for each line, but only include them in the result
1222                // if they differ from the old suggestion for that line.
1223                let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1224                let mut language_indent_size = IndentSize::default();
1225                for new_edited_row_range in new_edited_row_ranges {
1226                    let suggestions = snapshot
1227                        .suggest_autoindents(new_edited_row_range.clone())
1228                        .into_iter()
1229                        .flatten();
1230                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
1231                        if let Some(suggestion) = suggestion {
1232                            // Find the indent size based on the language for this row.
1233                            while let Some((row, size)) = language_indent_sizes.peek() {
1234                                if *row > new_row {
1235                                    break;
1236                                }
1237                                language_indent_size = *size;
1238                                language_indent_sizes.next();
1239                            }
1240
1241                            let suggested_indent = indent_sizes
1242                                .get(&suggestion.basis_row)
1243                                .copied()
1244                                .unwrap_or_else(|| {
1245                                    snapshot.indent_size_for_line(suggestion.basis_row)
1246                                })
1247                                .with_delta(suggestion.delta, language_indent_size);
1248                            if old_suggestions.get(&new_row).map_or(
1249                                true,
1250                                |(old_indentation, was_within_error)| {
1251                                    suggested_indent != *old_indentation
1252                                        && (!suggestion.within_error || *was_within_error)
1253                                },
1254                            ) {
1255                                indent_sizes.insert(new_row, suggested_indent);
1256                            }
1257                        }
1258                    }
1259                    yield_now().await;
1260                }
1261
1262                // For each block of inserted text, adjust the indentation of the remaining
1263                // lines of the block by the same amount as the first line was adjusted.
1264                if request.is_block_mode {
1265                    for (row_range, original_indent_column) in
1266                        row_ranges
1267                            .into_iter()
1268                            .filter_map(|(range, original_indent_column)| {
1269                                if range.len() > 1 {
1270                                    Some((range, original_indent_column?))
1271                                } else {
1272                                    None
1273                                }
1274                            })
1275                    {
1276                        let new_indent = indent_sizes
1277                            .get(&row_range.start)
1278                            .copied()
1279                            .unwrap_or_else(|| snapshot.indent_size_for_line(row_range.start));
1280                        let delta = new_indent.len as i64 - original_indent_column as i64;
1281                        if delta != 0 {
1282                            for row in row_range.skip(1) {
1283                                indent_sizes.entry(row).or_insert_with(|| {
1284                                    let mut size = snapshot.indent_size_for_line(row);
1285                                    if size.kind == new_indent.kind {
1286                                        match delta.cmp(&0) {
1287                                            Ordering::Greater => size.len += delta as u32,
1288                                            Ordering::Less => {
1289                                                size.len = size.len.saturating_sub(-delta as u32)
1290                                            }
1291                                            Ordering::Equal => {}
1292                                        }
1293                                    }
1294                                    size
1295                                });
1296                            }
1297                        }
1298                    }
1299                }
1300            }
1301
1302            indent_sizes
1303        })
1304    }
1305
1306    fn apply_autoindents(
1307        &mut self,
1308        indent_sizes: BTreeMap<u32, IndentSize>,
1309        cx: &mut ModelContext<Self>,
1310    ) {
1311        self.autoindent_requests.clear();
1312
1313        let edits: Vec<_> = indent_sizes
1314            .into_iter()
1315            .filter_map(|(row, indent_size)| {
1316                let current_size = indent_size_for_line(self, row);
1317                Self::edit_for_indent_size_adjustment(row, current_size, indent_size)
1318            })
1319            .collect();
1320
1321        self.edit(edits, None, cx);
1322    }
1323
1324    /// Create a minimal edit that will cause the given row to be indented
1325    /// with the given size. After applying this edit, the length of the line
1326    /// will always be at least `new_size.len`.
1327    pub fn edit_for_indent_size_adjustment(
1328        row: u32,
1329        current_size: IndentSize,
1330        new_size: IndentSize,
1331    ) -> Option<(Range<Point>, String)> {
1332        if new_size.kind == current_size.kind {
1333            match new_size.len.cmp(&current_size.len) {
1334                Ordering::Greater => {
1335                    let point = Point::new(row, 0);
1336                    Some((
1337                        point..point,
1338                        iter::repeat(new_size.char())
1339                            .take((new_size.len - current_size.len) as usize)
1340                            .collect::<String>(),
1341                    ))
1342                }
1343
1344                Ordering::Less => Some((
1345                    Point::new(row, 0)..Point::new(row, current_size.len - new_size.len),
1346                    String::new(),
1347                )),
1348
1349                Ordering::Equal => None,
1350            }
1351        } else {
1352            Some((
1353                Point::new(row, 0)..Point::new(row, current_size.len),
1354                iter::repeat(new_size.char())
1355                    .take(new_size.len as usize)
1356                    .collect::<String>(),
1357            ))
1358        }
1359    }
1360
1361    /// Spawns a background task that asynchronously computes a `Diff` between the buffer's text
1362    /// and the given new text.
1363    pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
1364        let old_text = self.as_rope().clone();
1365        let base_version = self.version();
1366        cx.background_executor()
1367            .spawn_labeled(*BUFFER_DIFF_TASK, async move {
1368                let old_text = old_text.to_string();
1369                let line_ending = LineEnding::detect(&new_text);
1370                LineEnding::normalize(&mut new_text);
1371
1372                let diff = TextDiff::from_chars(old_text.as_str(), new_text.as_str());
1373                let empty: Arc<str> = "".into();
1374
1375                let mut edits = Vec::new();
1376                let mut old_offset = 0;
1377                let mut new_offset = 0;
1378                let mut last_edit: Option<(Range<usize>, Range<usize>)> = None;
1379                for change in diff.iter_all_changes().map(Some).chain([None]) {
1380                    if let Some(change) = &change {
1381                        let len = change.value().len();
1382                        match change.tag() {
1383                            ChangeTag::Equal => {
1384                                old_offset += len;
1385                                new_offset += len;
1386                            }
1387                            ChangeTag::Delete => {
1388                                let old_end_offset = old_offset + len;
1389                                if let Some((last_old_range, _)) = &mut last_edit {
1390                                    last_old_range.end = old_end_offset;
1391                                } else {
1392                                    last_edit =
1393                                        Some((old_offset..old_end_offset, new_offset..new_offset));
1394                                }
1395                                old_offset = old_end_offset;
1396                            }
1397                            ChangeTag::Insert => {
1398                                let new_end_offset = new_offset + len;
1399                                if let Some((_, last_new_range)) = &mut last_edit {
1400                                    last_new_range.end = new_end_offset;
1401                                } else {
1402                                    last_edit =
1403                                        Some((old_offset..old_offset, new_offset..new_end_offset));
1404                                }
1405                                new_offset = new_end_offset;
1406                            }
1407                        }
1408                    }
1409
1410                    if let Some((old_range, new_range)) = &last_edit {
1411                        if old_offset > old_range.end
1412                            || new_offset > new_range.end
1413                            || change.is_none()
1414                        {
1415                            let text = if new_range.is_empty() {
1416                                empty.clone()
1417                            } else {
1418                                new_text[new_range.clone()].into()
1419                            };
1420                            edits.push((old_range.clone(), text));
1421                            last_edit.take();
1422                        }
1423                    }
1424                }
1425
1426                Diff {
1427                    base_version,
1428                    line_ending,
1429                    edits,
1430                }
1431            })
1432    }
1433
1434    /// Spawns a background task that searches the buffer for any whitespace
1435    /// at the ends of a lines, and returns a `Diff` that removes that whitespace.
1436    pub fn remove_trailing_whitespace(&self, cx: &AppContext) -> Task<Diff> {
1437        let old_text = self.as_rope().clone();
1438        let line_ending = self.line_ending();
1439        let base_version = self.version();
1440        cx.background_executor().spawn(async move {
1441            let ranges = trailing_whitespace_ranges(&old_text);
1442            let empty = Arc::<str>::from("");
1443            Diff {
1444                base_version,
1445                line_ending,
1446                edits: ranges
1447                    .into_iter()
1448                    .map(|range| (range, empty.clone()))
1449                    .collect(),
1450            }
1451        })
1452    }
1453
1454    /// Ensures that the buffer ends with a single newline character, and
1455    /// no other whitespace.
1456    pub fn ensure_final_newline(&mut self, cx: &mut ModelContext<Self>) {
1457        let len = self.len();
1458        let mut offset = len;
1459        for chunk in self.as_rope().reversed_chunks_in_range(0..len) {
1460            let non_whitespace_len = chunk
1461                .trim_end_matches(|c: char| c.is_ascii_whitespace())
1462                .len();
1463            offset -= chunk.len();
1464            offset += non_whitespace_len;
1465            if non_whitespace_len != 0 {
1466                if offset == len - 1 && chunk.get(non_whitespace_len..) == Some("\n") {
1467                    return;
1468                }
1469                break;
1470            }
1471        }
1472        self.edit([(offset..len, "\n")], None, cx);
1473    }
1474
1475    /// Applies a diff to the buffer. If the buffer has changed since the given diff was
1476    /// calculated, then adjust the diff to account for those changes, and discard any
1477    /// parts of the diff that conflict with those changes.
1478    pub fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1479        // Check for any edits to the buffer that have occurred since this diff
1480        // was computed.
1481        let snapshot = self.snapshot();
1482        let mut edits_since = snapshot.edits_since::<usize>(&diff.base_version).peekable();
1483        let mut delta = 0;
1484        let adjusted_edits = diff.edits.into_iter().filter_map(|(range, new_text)| {
1485            while let Some(edit_since) = edits_since.peek() {
1486                // If the edit occurs after a diff hunk, then it does not
1487                // affect that hunk.
1488                if edit_since.old.start > range.end {
1489                    break;
1490                }
1491                // If the edit precedes the diff hunk, then adjust the hunk
1492                // to reflect the edit.
1493                else if edit_since.old.end < range.start {
1494                    delta += edit_since.new_len() as i64 - edit_since.old_len() as i64;
1495                    edits_since.next();
1496                }
1497                // If the edit intersects a diff hunk, then discard that hunk.
1498                else {
1499                    return None;
1500                }
1501            }
1502
1503            let start = (range.start as i64 + delta) as usize;
1504            let end = (range.end as i64 + delta) as usize;
1505            Some((start..end, new_text))
1506        });
1507
1508        self.start_transaction();
1509        self.text.set_line_ending(diff.line_ending);
1510        self.edit(adjusted_edits, None, cx);
1511        self.end_transaction(cx)
1512    }
1513
1514    fn changed_since_saved_version(&self) -> bool {
1515        self.edits_since::<usize>(&self.saved_version)
1516            .next()
1517            .is_some()
1518    }
1519    /// Checks if the buffer has unsaved changes.
1520    pub fn is_dirty(&self) -> bool {
1521        (self.has_conflict || self.changed_since_saved_version())
1522            || self
1523                .file
1524                .as_ref()
1525                .map_or(false, |file| file.is_deleted() || !file.is_created())
1526    }
1527
1528    /// Checks if the buffer and its file have both changed since the buffer
1529    /// was last saved or reloaded.
1530    pub fn has_conflict(&self) -> bool {
1531        (self.has_conflict || self.changed_since_saved_version())
1532            && self
1533                .file
1534                .as_ref()
1535                .map_or(false, |file| file.mtime() > self.saved_mtime)
1536    }
1537
1538    /// Gets a [`Subscription`] that tracks all of the changes to the buffer's text.
1539    pub fn subscribe(&mut self) -> Subscription {
1540        self.text.subscribe()
1541    }
1542
1543    /// Starts a transaction, if one is not already in-progress. When undoing or
1544    /// redoing edits, all of the edits performed within a transaction are undone
1545    /// or redone together.
1546    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1547        self.start_transaction_at(Instant::now())
1548    }
1549
1550    /// Starts a transaction, providing the current time. Subsequent transactions
1551    /// that occur within a short period of time will be grouped together. This
1552    /// is controlled by the buffer's undo grouping duration.
1553    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1554        self.transaction_depth += 1;
1555        if self.was_dirty_before_starting_transaction.is_none() {
1556            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
1557        }
1558        self.text.start_transaction_at(now)
1559    }
1560
1561    /// Terminates the current transaction, if this is the outermost transaction.
1562    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1563        self.end_transaction_at(Instant::now(), cx)
1564    }
1565
1566    /// Terminates the current transaction, providing the current time. Subsequent transactions
1567    /// that occur within a short period of time will be grouped together. This
1568    /// is controlled by the buffer's undo grouping duration.
1569    pub fn end_transaction_at(
1570        &mut self,
1571        now: Instant,
1572        cx: &mut ModelContext<Self>,
1573    ) -> Option<TransactionId> {
1574        assert!(self.transaction_depth > 0);
1575        self.transaction_depth -= 1;
1576        let was_dirty = if self.transaction_depth == 0 {
1577            self.was_dirty_before_starting_transaction.take().unwrap()
1578        } else {
1579            false
1580        };
1581        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1582            self.did_edit(&start_version, was_dirty, cx);
1583            Some(transaction_id)
1584        } else {
1585            None
1586        }
1587    }
1588
1589    /// Manually add a transaction to the buffer's undo history.
1590    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1591        self.text.push_transaction(transaction, now);
1592    }
1593
1594    /// Prevent the last transaction from being grouped with any subsequent transactions,
1595    /// even if they occur with the buffer's undo grouping duration.
1596    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1597        self.text.finalize_last_transaction()
1598    }
1599
1600    /// Manually group all changes since a given transaction.
1601    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
1602        self.text.group_until_transaction(transaction_id);
1603    }
1604
1605    /// Manually remove a transaction from the buffer's undo history
1606    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1607        self.text.forget_transaction(transaction_id);
1608    }
1609
1610    /// Manually merge two adjacent transactions in the buffer's undo history.
1611    pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
1612        self.text.merge_transactions(transaction, destination);
1613    }
1614
1615    /// Waits for the buffer to receive operations with the given timestamps.
1616    pub fn wait_for_edits(
1617        &mut self,
1618        edit_ids: impl IntoIterator<Item = clock::Lamport>,
1619    ) -> impl Future<Output = Result<()>> {
1620        self.text.wait_for_edits(edit_ids)
1621    }
1622
1623    /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
1624    pub fn wait_for_anchors(
1625        &mut self,
1626        anchors: impl IntoIterator<Item = Anchor>,
1627    ) -> impl 'static + Future<Output = Result<()>> {
1628        self.text.wait_for_anchors(anchors)
1629    }
1630
1631    /// Waits for the buffer to receive operations up to the given version.
1632    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
1633        self.text.wait_for_version(version)
1634    }
1635
1636    /// Forces all futures returned by [`Buffer::wait_for_version`], [`Buffer::wait_for_edits`], or
1637    /// [`Buffer::wait_for_version`] to resolve with an error.
1638    pub fn give_up_waiting(&mut self) {
1639        self.text.give_up_waiting();
1640    }
1641
1642    /// Stores a set of selections that should be broadcasted to all of the buffer's replicas.
1643    pub fn set_active_selections(
1644        &mut self,
1645        selections: Arc<[Selection<Anchor>]>,
1646        line_mode: bool,
1647        cursor_shape: CursorShape,
1648        cx: &mut ModelContext<Self>,
1649    ) {
1650        let lamport_timestamp = self.text.lamport_clock.tick();
1651        self.remote_selections.insert(
1652            self.text.replica_id(),
1653            SelectionSet {
1654                selections: selections.clone(),
1655                lamport_timestamp,
1656                line_mode,
1657                cursor_shape,
1658            },
1659        );
1660        self.send_operation(
1661            Operation::UpdateSelections {
1662                selections,
1663                line_mode,
1664                lamport_timestamp,
1665                cursor_shape,
1666            },
1667            cx,
1668        );
1669    }
1670
1671    /// Clears the selections, so that other replicas of the buffer do not see any selections for
1672    /// this replica.
1673    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1674        if self
1675            .remote_selections
1676            .get(&self.text.replica_id())
1677            .map_or(true, |set| !set.selections.is_empty())
1678        {
1679            self.set_active_selections(Arc::from([]), false, Default::default(), cx);
1680        }
1681    }
1682
1683    /// Replaces the buffer's entire text.
1684    pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Lamport>
1685    where
1686        T: Into<Arc<str>>,
1687    {
1688        self.autoindent_requests.clear();
1689        self.edit([(0..self.len(), text)], None, cx)
1690    }
1691
1692    /// Applies the given edits to the buffer. Each edit is specified as a range of text to
1693    /// delete, and a string of text to insert at that location.
1694    ///
1695    /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
1696    /// request for the edited ranges, which will be processed when the buffer finishes
1697    /// parsing.
1698    ///
1699    /// Parsing takes place at the end of a transaction, and may compute synchronously
1700    /// or asynchronously, depending on the changes.
1701    pub fn edit<I, S, T>(
1702        &mut self,
1703        edits_iter: I,
1704        autoindent_mode: Option<AutoindentMode>,
1705        cx: &mut ModelContext<Self>,
1706    ) -> Option<clock::Lamport>
1707    where
1708        I: IntoIterator<Item = (Range<S>, T)>,
1709        S: ToOffset,
1710        T: Into<Arc<str>>,
1711    {
1712        // Skip invalid edits and coalesce contiguous ones.
1713        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1714        for (range, new_text) in edits_iter {
1715            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1716            if range.start > range.end {
1717                mem::swap(&mut range.start, &mut range.end);
1718            }
1719            let new_text = new_text.into();
1720            if !new_text.is_empty() || !range.is_empty() {
1721                if let Some((prev_range, prev_text)) = edits.last_mut() {
1722                    if prev_range.end >= range.start {
1723                        prev_range.end = cmp::max(prev_range.end, range.end);
1724                        *prev_text = format!("{prev_text}{new_text}").into();
1725                    } else {
1726                        edits.push((range, new_text));
1727                    }
1728                } else {
1729                    edits.push((range, new_text));
1730                }
1731            }
1732        }
1733        if edits.is_empty() {
1734            return None;
1735        }
1736
1737        self.start_transaction();
1738        self.pending_autoindent.take();
1739        let autoindent_request = autoindent_mode
1740            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
1741
1742        let edit_operation = self.text.edit(edits.iter().cloned());
1743        let edit_id = edit_operation.timestamp();
1744
1745        if let Some((before_edit, mode)) = autoindent_request {
1746            let mut delta = 0isize;
1747            let entries = edits
1748                .into_iter()
1749                .enumerate()
1750                .zip(&edit_operation.as_edit().unwrap().new_text)
1751                .map(|((ix, (range, _)), new_text)| {
1752                    let new_text_length = new_text.len();
1753                    let old_start = range.start.to_point(&before_edit);
1754                    let new_start = (delta + range.start as isize) as usize;
1755                    delta += new_text_length as isize - (range.end as isize - range.start as isize);
1756
1757                    let mut range_of_insertion_to_indent = 0..new_text_length;
1758                    let mut first_line_is_new = false;
1759                    let mut original_indent_column = None;
1760
1761                    // When inserting an entire line at the beginning of an existing line,
1762                    // treat the insertion as new.
1763                    if new_text.contains('\n')
1764                        && old_start.column <= before_edit.indent_size_for_line(old_start.row).len
1765                    {
1766                        first_line_is_new = true;
1767                    }
1768
1769                    // When inserting text starting with a newline, avoid auto-indenting the
1770                    // previous line.
1771                    if new_text.starts_with('\n') {
1772                        range_of_insertion_to_indent.start += 1;
1773                        first_line_is_new = true;
1774                    }
1775
1776                    // Avoid auto-indenting after the insertion.
1777                    if let AutoindentMode::Block {
1778                        original_indent_columns,
1779                    } = &mode
1780                    {
1781                        original_indent_column =
1782                            Some(original_indent_columns.get(ix).copied().unwrap_or_else(|| {
1783                                indent_size_for_text(
1784                                    new_text[range_of_insertion_to_indent.clone()].chars(),
1785                                )
1786                                .len
1787                            }));
1788                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
1789                            range_of_insertion_to_indent.end -= 1;
1790                        }
1791                    }
1792
1793                    AutoindentRequestEntry {
1794                        first_line_is_new,
1795                        original_indent_column,
1796                        indent_size: before_edit.language_indent_size_at(range.start, cx),
1797                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
1798                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
1799                    }
1800                })
1801                .collect();
1802
1803            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1804                before_edit,
1805                entries,
1806                is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
1807            }));
1808        }
1809
1810        self.end_transaction(cx);
1811        self.send_operation(Operation::Buffer(edit_operation), cx);
1812        Some(edit_id)
1813    }
1814
1815    fn did_edit(
1816        &mut self,
1817        old_version: &clock::Global,
1818        was_dirty: bool,
1819        cx: &mut ModelContext<Self>,
1820    ) {
1821        if self.edits_since::<usize>(old_version).next().is_none() {
1822            return;
1823        }
1824
1825        self.reparse(cx);
1826
1827        cx.emit(Event::Edited);
1828        if was_dirty != self.is_dirty() {
1829            cx.emit(Event::DirtyChanged);
1830        }
1831        cx.notify();
1832    }
1833
1834    /// Applies the given remote operations to the buffer.
1835    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1836        &mut self,
1837        ops: I,
1838        cx: &mut ModelContext<Self>,
1839    ) -> Result<()> {
1840        self.pending_autoindent.take();
1841        let was_dirty = self.is_dirty();
1842        let old_version = self.version.clone();
1843        let mut deferred_ops = Vec::new();
1844        let buffer_ops = ops
1845            .into_iter()
1846            .filter_map(|op| match op {
1847                Operation::Buffer(op) => Some(op),
1848                _ => {
1849                    if self.can_apply_op(&op) {
1850                        self.apply_op(op, cx);
1851                    } else {
1852                        deferred_ops.push(op);
1853                    }
1854                    None
1855                }
1856            })
1857            .collect::<Vec<_>>();
1858        self.text.apply_ops(buffer_ops)?;
1859        self.deferred_ops.insert(deferred_ops);
1860        self.flush_deferred_ops(cx);
1861        self.did_edit(&old_version, was_dirty, cx);
1862        // Notify independently of whether the buffer was edited as the operations could include a
1863        // selection update.
1864        cx.notify();
1865        Ok(())
1866    }
1867
1868    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1869        let mut deferred_ops = Vec::new();
1870        for op in self.deferred_ops.drain().iter().cloned() {
1871            if self.can_apply_op(&op) {
1872                self.apply_op(op, cx);
1873            } else {
1874                deferred_ops.push(op);
1875            }
1876        }
1877        self.deferred_ops.insert(deferred_ops);
1878    }
1879
1880    fn can_apply_op(&self, operation: &Operation) -> bool {
1881        match operation {
1882            Operation::Buffer(_) => {
1883                unreachable!("buffer operations should never be applied at this layer")
1884            }
1885            Operation::UpdateDiagnostics {
1886                diagnostics: diagnostic_set,
1887                ..
1888            } => diagnostic_set.iter().all(|diagnostic| {
1889                self.text.can_resolve(&diagnostic.range.start)
1890                    && self.text.can_resolve(&diagnostic.range.end)
1891            }),
1892            Operation::UpdateSelections { selections, .. } => selections
1893                .iter()
1894                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1895            Operation::UpdateCompletionTriggers { .. } => true,
1896        }
1897    }
1898
1899    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1900        match operation {
1901            Operation::Buffer(_) => {
1902                unreachable!("buffer operations should never be applied at this layer")
1903            }
1904            Operation::UpdateDiagnostics {
1905                server_id,
1906                diagnostics: diagnostic_set,
1907                lamport_timestamp,
1908            } => {
1909                let snapshot = self.snapshot();
1910                self.apply_diagnostic_update(
1911                    server_id,
1912                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1913                    lamport_timestamp,
1914                    cx,
1915                );
1916            }
1917            Operation::UpdateSelections {
1918                selections,
1919                lamport_timestamp,
1920                line_mode,
1921                cursor_shape,
1922            } => {
1923                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
1924                    if set.lamport_timestamp > lamport_timestamp {
1925                        return;
1926                    }
1927                }
1928
1929                self.remote_selections.insert(
1930                    lamport_timestamp.replica_id,
1931                    SelectionSet {
1932                        selections,
1933                        lamport_timestamp,
1934                        line_mode,
1935                        cursor_shape,
1936                    },
1937                );
1938                self.text.lamport_clock.observe(lamport_timestamp);
1939                self.selections_update_count += 1;
1940            }
1941            Operation::UpdateCompletionTriggers {
1942                triggers,
1943                lamport_timestamp,
1944            } => {
1945                self.completion_triggers = triggers;
1946                self.text.lamport_clock.observe(lamport_timestamp);
1947            }
1948        }
1949    }
1950
1951    fn apply_diagnostic_update(
1952        &mut self,
1953        server_id: LanguageServerId,
1954        diagnostics: DiagnosticSet,
1955        lamport_timestamp: clock::Lamport,
1956        cx: &mut ModelContext<Self>,
1957    ) {
1958        if lamport_timestamp > self.diagnostics_timestamp {
1959            let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
1960            if diagnostics.len() == 0 {
1961                if let Ok(ix) = ix {
1962                    self.diagnostics.remove(ix);
1963                }
1964            } else {
1965                match ix {
1966                    Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
1967                    Ok(ix) => self.diagnostics[ix].1 = diagnostics,
1968                };
1969            }
1970            self.diagnostics_timestamp = lamport_timestamp;
1971            self.diagnostics_update_count += 1;
1972            self.text.lamport_clock.observe(lamport_timestamp);
1973            cx.notify();
1974            cx.emit(Event::DiagnosticsUpdated);
1975        }
1976    }
1977
1978    fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1979        cx.emit(Event::Operation(operation));
1980    }
1981
1982    /// Removes the selections for a given peer.
1983    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1984        self.remote_selections.remove(&replica_id);
1985        cx.notify();
1986    }
1987
1988    /// Undoes the most recent transaction.
1989    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1990        let was_dirty = self.is_dirty();
1991        let old_version = self.version.clone();
1992
1993        if let Some((transaction_id, operation)) = self.text.undo() {
1994            self.send_operation(Operation::Buffer(operation), cx);
1995            self.did_edit(&old_version, was_dirty, cx);
1996            Some(transaction_id)
1997        } else {
1998            None
1999        }
2000    }
2001
2002    /// Manually undoes a specific transaction in the buffer's undo history.
2003    pub fn undo_transaction(
2004        &mut self,
2005        transaction_id: TransactionId,
2006        cx: &mut ModelContext<Self>,
2007    ) -> bool {
2008        let was_dirty = self.is_dirty();
2009        let old_version = self.version.clone();
2010        if let Some(operation) = self.text.undo_transaction(transaction_id) {
2011            self.send_operation(Operation::Buffer(operation), cx);
2012            self.did_edit(&old_version, was_dirty, cx);
2013            true
2014        } else {
2015            false
2016        }
2017    }
2018
2019    /// Manually undoes all changes after a given transaction in the buffer's undo history.
2020    pub fn undo_to_transaction(
2021        &mut self,
2022        transaction_id: TransactionId,
2023        cx: &mut ModelContext<Self>,
2024    ) -> bool {
2025        let was_dirty = self.is_dirty();
2026        let old_version = self.version.clone();
2027
2028        let operations = self.text.undo_to_transaction(transaction_id);
2029        let undone = !operations.is_empty();
2030        for operation in operations {
2031            self.send_operation(Operation::Buffer(operation), cx);
2032        }
2033        if undone {
2034            self.did_edit(&old_version, was_dirty, cx)
2035        }
2036        undone
2037    }
2038
2039    /// Manually redoes a specific transaction in the buffer's redo history.
2040    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
2041        let was_dirty = self.is_dirty();
2042        let old_version = self.version.clone();
2043
2044        if let Some((transaction_id, operation)) = self.text.redo() {
2045            self.send_operation(Operation::Buffer(operation), cx);
2046            self.did_edit(&old_version, was_dirty, cx);
2047            Some(transaction_id)
2048        } else {
2049            None
2050        }
2051    }
2052
2053    /// Manually undoes all changes until a given transaction in the buffer's redo history.
2054    pub fn redo_to_transaction(
2055        &mut self,
2056        transaction_id: TransactionId,
2057        cx: &mut ModelContext<Self>,
2058    ) -> bool {
2059        let was_dirty = self.is_dirty();
2060        let old_version = self.version.clone();
2061
2062        let operations = self.text.redo_to_transaction(transaction_id);
2063        let redone = !operations.is_empty();
2064        for operation in operations {
2065            self.send_operation(Operation::Buffer(operation), cx);
2066        }
2067        if redone {
2068            self.did_edit(&old_version, was_dirty, cx)
2069        }
2070        redone
2071    }
2072
2073    /// Override current completion triggers with the user-provided completion triggers.
2074    pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
2075        self.completion_triggers = triggers.clone();
2076        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2077        self.send_operation(
2078            Operation::UpdateCompletionTriggers {
2079                triggers,
2080                lamport_timestamp: self.completion_triggers_timestamp,
2081            },
2082            cx,
2083        );
2084        cx.notify();
2085    }
2086
2087    /// Returns a list of strings which trigger a completion menu for this language.
2088    /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2089    pub fn completion_triggers(&self) -> &[String] {
2090        &self.completion_triggers
2091    }
2092}
2093
2094#[doc(hidden)]
2095#[cfg(any(test, feature = "test-support"))]
2096impl Buffer {
2097    pub fn edit_via_marked_text(
2098        &mut self,
2099        marked_string: &str,
2100        autoindent_mode: Option<AutoindentMode>,
2101        cx: &mut ModelContext<Self>,
2102    ) {
2103        let edits = self.edits_for_marked_text(marked_string);
2104        self.edit(edits, autoindent_mode, cx);
2105    }
2106
2107    pub fn set_group_interval(&mut self, group_interval: Duration) {
2108        self.text.set_group_interval(group_interval);
2109    }
2110
2111    pub fn randomly_edit<T>(
2112        &mut self,
2113        rng: &mut T,
2114        old_range_count: usize,
2115        cx: &mut ModelContext<Self>,
2116    ) where
2117        T: rand::Rng,
2118    {
2119        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2120        let mut last_end = None;
2121        for _ in 0..old_range_count {
2122            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2123                break;
2124            }
2125
2126            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2127            let mut range = self.random_byte_range(new_start, rng);
2128            if rng.gen_bool(0.2) {
2129                mem::swap(&mut range.start, &mut range.end);
2130            }
2131            last_end = Some(range.end);
2132
2133            let new_text_len = rng.gen_range(0..10);
2134            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2135
2136            edits.push((range, new_text));
2137        }
2138        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2139        self.edit(edits, None, cx);
2140    }
2141
2142    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
2143        let was_dirty = self.is_dirty();
2144        let old_version = self.version.clone();
2145
2146        let ops = self.text.randomly_undo_redo(rng);
2147        if !ops.is_empty() {
2148            for op in ops {
2149                self.send_operation(Operation::Buffer(op), cx);
2150                self.did_edit(&old_version, was_dirty, cx);
2151            }
2152        }
2153    }
2154}
2155
2156impl EventEmitter<Event> for Buffer {}
2157
2158impl Deref for Buffer {
2159    type Target = TextBuffer;
2160
2161    fn deref(&self) -> &Self::Target {
2162        &self.text
2163    }
2164}
2165
2166impl BufferSnapshot {
2167    /// Returns [`IndentSize`] for a given line that respects user settings and /// language preferences.
2168    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2169        indent_size_for_line(self, row)
2170    }
2171    /// Returns [`IndentSize`] for a given position that respects user settings
2172    /// and language preferences.
2173    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &AppContext) -> IndentSize {
2174        let settings = language_settings(self.language_at(position), self.file(), cx);
2175        if settings.hard_tabs {
2176            IndentSize::tab()
2177        } else {
2178            IndentSize::spaces(settings.tab_size.get())
2179        }
2180    }
2181
2182    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2183    /// is passed in as `single_indent_size`.
2184    pub fn suggested_indents(
2185        &self,
2186        rows: impl Iterator<Item = u32>,
2187        single_indent_size: IndentSize,
2188    ) -> BTreeMap<u32, IndentSize> {
2189        let mut result = BTreeMap::new();
2190
2191        for row_range in contiguous_ranges(rows, 10) {
2192            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2193                Some(suggestions) => suggestions,
2194                _ => break,
2195            };
2196
2197            for (row, suggestion) in row_range.zip(suggestions) {
2198                let indent_size = if let Some(suggestion) = suggestion {
2199                    result
2200                        .get(&suggestion.basis_row)
2201                        .copied()
2202                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2203                        .with_delta(suggestion.delta, single_indent_size)
2204                } else {
2205                    self.indent_size_for_line(row)
2206                };
2207
2208                result.insert(row, indent_size);
2209            }
2210        }
2211
2212        result
2213    }
2214
2215    fn suggest_autoindents(
2216        &self,
2217        row_range: Range<u32>,
2218    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2219        let config = &self.language.as_ref()?.config;
2220        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2221
2222        // Find the suggested indentation ranges based on the syntax tree.
2223        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2224        let end = Point::new(row_range.end, 0);
2225        let range = (start..end).to_offset(&self.text);
2226        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2227            Some(&grammar.indents_config.as_ref()?.query)
2228        });
2229        let indent_configs = matches
2230            .grammars()
2231            .iter()
2232            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2233            .collect::<Vec<_>>();
2234
2235        let mut indent_ranges = Vec::<Range<Point>>::new();
2236        let mut outdent_positions = Vec::<Point>::new();
2237        while let Some(mat) = matches.peek() {
2238            let mut start: Option<Point> = None;
2239            let mut end: Option<Point> = None;
2240
2241            let config = &indent_configs[mat.grammar_index];
2242            for capture in mat.captures {
2243                if capture.index == config.indent_capture_ix {
2244                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2245                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2246                } else if Some(capture.index) == config.start_capture_ix {
2247                    start = Some(Point::from_ts_point(capture.node.end_position()));
2248                } else if Some(capture.index) == config.end_capture_ix {
2249                    end = Some(Point::from_ts_point(capture.node.start_position()));
2250                } else if Some(capture.index) == config.outdent_capture_ix {
2251                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2252                }
2253            }
2254
2255            matches.advance();
2256            if let Some((start, end)) = start.zip(end) {
2257                if start.row == end.row {
2258                    continue;
2259                }
2260
2261                let range = start..end;
2262                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2263                    Err(ix) => indent_ranges.insert(ix, range),
2264                    Ok(ix) => {
2265                        let prev_range = &mut indent_ranges[ix];
2266                        prev_range.end = prev_range.end.max(range.end);
2267                    }
2268                }
2269            }
2270        }
2271
2272        let mut error_ranges = Vec::<Range<Point>>::new();
2273        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2274            Some(&grammar.error_query)
2275        });
2276        while let Some(mat) = matches.peek() {
2277            let node = mat.captures[0].node;
2278            let start = Point::from_ts_point(node.start_position());
2279            let end = Point::from_ts_point(node.end_position());
2280            let range = start..end;
2281            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2282                Ok(ix) | Err(ix) => ix,
2283            };
2284            let mut end_ix = ix;
2285            while let Some(existing_range) = error_ranges.get(end_ix) {
2286                if existing_range.end < end {
2287                    end_ix += 1;
2288                } else {
2289                    break;
2290                }
2291            }
2292            error_ranges.splice(ix..end_ix, [range]);
2293            matches.advance();
2294        }
2295
2296        outdent_positions.sort();
2297        for outdent_position in outdent_positions {
2298            // find the innermost indent range containing this outdent_position
2299            // set its end to the outdent position
2300            if let Some(range_to_truncate) = indent_ranges
2301                .iter_mut()
2302                .filter(|indent_range| indent_range.contains(&outdent_position))
2303                .last()
2304            {
2305                range_to_truncate.end = outdent_position;
2306            }
2307        }
2308
2309        // Find the suggested indentation increases and decreased based on regexes.
2310        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2311        self.for_each_line(
2312            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2313                ..Point::new(row_range.end, 0),
2314            |row, line| {
2315                if config
2316                    .decrease_indent_pattern
2317                    .as_ref()
2318                    .map_or(false, |regex| regex.is_match(line))
2319                {
2320                    indent_change_rows.push((row, Ordering::Less));
2321                }
2322                if config
2323                    .increase_indent_pattern
2324                    .as_ref()
2325                    .map_or(false, |regex| regex.is_match(line))
2326                {
2327                    indent_change_rows.push((row + 1, Ordering::Greater));
2328                }
2329            },
2330        );
2331
2332        let mut indent_changes = indent_change_rows.into_iter().peekable();
2333        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2334            prev_non_blank_row.unwrap_or(0)
2335        } else {
2336            row_range.start.saturating_sub(1)
2337        };
2338        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2339        Some(row_range.map(move |row| {
2340            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2341
2342            let mut indent_from_prev_row = false;
2343            let mut outdent_from_prev_row = false;
2344            let mut outdent_to_row = u32::MAX;
2345
2346            while let Some((indent_row, delta)) = indent_changes.peek() {
2347                match indent_row.cmp(&row) {
2348                    Ordering::Equal => match delta {
2349                        Ordering::Less => outdent_from_prev_row = true,
2350                        Ordering::Greater => indent_from_prev_row = true,
2351                        _ => {}
2352                    },
2353
2354                    Ordering::Greater => break,
2355                    Ordering::Less => {}
2356                }
2357
2358                indent_changes.next();
2359            }
2360
2361            for range in &indent_ranges {
2362                if range.start.row >= row {
2363                    break;
2364                }
2365                if range.start.row == prev_row && range.end > row_start {
2366                    indent_from_prev_row = true;
2367                }
2368                if range.end > prev_row_start && range.end <= row_start {
2369                    outdent_to_row = outdent_to_row.min(range.start.row);
2370                }
2371            }
2372
2373            let within_error = error_ranges
2374                .iter()
2375                .any(|e| e.start.row < row && e.end > row_start);
2376
2377            let suggestion = if outdent_to_row == prev_row
2378                || (outdent_from_prev_row && indent_from_prev_row)
2379            {
2380                Some(IndentSuggestion {
2381                    basis_row: prev_row,
2382                    delta: Ordering::Equal,
2383                    within_error,
2384                })
2385            } else if indent_from_prev_row {
2386                Some(IndentSuggestion {
2387                    basis_row: prev_row,
2388                    delta: Ordering::Greater,
2389                    within_error,
2390                })
2391            } else if outdent_to_row < prev_row {
2392                Some(IndentSuggestion {
2393                    basis_row: outdent_to_row,
2394                    delta: Ordering::Equal,
2395                    within_error,
2396                })
2397            } else if outdent_from_prev_row {
2398                Some(IndentSuggestion {
2399                    basis_row: prev_row,
2400                    delta: Ordering::Less,
2401                    within_error,
2402                })
2403            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
2404            {
2405                Some(IndentSuggestion {
2406                    basis_row: prev_row,
2407                    delta: Ordering::Equal,
2408                    within_error,
2409                })
2410            } else {
2411                None
2412            };
2413
2414            prev_row = row;
2415            prev_row_start = row_start;
2416            suggestion
2417        }))
2418    }
2419
2420    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2421        while row > 0 {
2422            row -= 1;
2423            if !self.is_line_blank(row) {
2424                return Some(row);
2425            }
2426        }
2427        None
2428    }
2429
2430    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
2431    /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
2432    /// returned in chunks where each chunk has a single syntax highlighting style and
2433    /// diagnostic status.
2434    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
2435        let range = range.start.to_offset(self)..range.end.to_offset(self);
2436
2437        let mut syntax = None;
2438        let mut diagnostic_endpoints = Vec::new();
2439        if language_aware {
2440            let captures = self.syntax.captures(range.clone(), &self.text, |grammar| {
2441                grammar.highlights_query.as_ref()
2442            });
2443            let highlight_maps = captures
2444                .grammars()
2445                .into_iter()
2446                .map(|grammar| grammar.highlight_map())
2447                .collect();
2448            syntax = Some((captures, highlight_maps));
2449            for entry in self.diagnostics_in_range::<_, usize>(range.clone(), false) {
2450                diagnostic_endpoints.push(DiagnosticEndpoint {
2451                    offset: entry.range.start,
2452                    is_start: true,
2453                    severity: entry.diagnostic.severity,
2454                    is_unnecessary: entry.diagnostic.is_unnecessary,
2455                });
2456                diagnostic_endpoints.push(DiagnosticEndpoint {
2457                    offset: entry.range.end,
2458                    is_start: false,
2459                    severity: entry.diagnostic.severity,
2460                    is_unnecessary: entry.diagnostic.is_unnecessary,
2461                });
2462            }
2463            diagnostic_endpoints
2464                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
2465        }
2466
2467        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostic_endpoints)
2468    }
2469
2470    /// Invokes the given callback for each line of text in the given range of the buffer.
2471    /// Uses callback to avoid allocating a string for each line.
2472    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
2473        let mut line = String::new();
2474        let mut row = range.start.row;
2475        for chunk in self
2476            .as_rope()
2477            .chunks_in_range(range.to_offset(self))
2478            .chain(["\n"])
2479        {
2480            for (newline_ix, text) in chunk.split('\n').enumerate() {
2481                if newline_ix > 0 {
2482                    callback(row, &line);
2483                    row += 1;
2484                    line.clear();
2485                }
2486                line.push_str(text);
2487            }
2488        }
2489    }
2490
2491    /// Iterates over every [`SyntaxLayer`] in the buffer.
2492    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
2493        self.syntax.layers_for_range(0..self.len(), &self.text)
2494    }
2495
2496    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
2497        let offset = position.to_offset(self);
2498        self.syntax
2499            .layers_for_range(offset..offset, &self.text)
2500            .filter(|l| l.node().end_byte() > offset)
2501            .last()
2502    }
2503
2504    /// Returns the main [Language]
2505    pub fn language(&self) -> Option<&Arc<Language>> {
2506        self.language.as_ref()
2507    }
2508
2509    /// Returns the [Language] at the given location.
2510    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
2511        self.syntax_layer_at(position)
2512            .map(|info| info.language)
2513            .or(self.language.as_ref())
2514    }
2515
2516    /// Returns the settings for the language at the given location.
2517    pub fn settings_at<'a, D: ToOffset>(
2518        &self,
2519        position: D,
2520        cx: &'a AppContext,
2521    ) -> &'a LanguageSettings {
2522        language_settings(self.language_at(position), self.file.as_ref(), cx)
2523    }
2524
2525    /// Returns the [LanguageScope] at the given location.
2526    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
2527        let offset = position.to_offset(self);
2528        let mut scope = None;
2529        let mut smallest_range: Option<Range<usize>> = None;
2530
2531        // Use the layer that has the smallest node intersecting the given point.
2532        for layer in self.syntax.layers_for_range(offset..offset, &self.text) {
2533            let mut cursor = layer.node().walk();
2534
2535            let mut range = None;
2536            loop {
2537                let child_range = cursor.node().byte_range();
2538                if !child_range.to_inclusive().contains(&offset) {
2539                    break;
2540                }
2541
2542                range = Some(child_range);
2543                if cursor.goto_first_child_for_byte(offset).is_none() {
2544                    break;
2545                }
2546            }
2547
2548            if let Some(range) = range {
2549                if smallest_range
2550                    .as_ref()
2551                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
2552                {
2553                    smallest_range = Some(range);
2554                    scope = Some(LanguageScope {
2555                        language: layer.language.clone(),
2556                        override_id: layer.override_id(offset, &self.text),
2557                    });
2558                }
2559            }
2560        }
2561
2562        scope.or_else(|| {
2563            self.language.clone().map(|language| LanguageScope {
2564                language,
2565                override_id: None,
2566            })
2567        })
2568    }
2569
2570    /// Returns a tuple of the range and character kind of the word
2571    /// surrounding the given position.
2572    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2573        let mut start = start.to_offset(self);
2574        let mut end = start;
2575        let mut next_chars = self.chars_at(start).peekable();
2576        let mut prev_chars = self.reversed_chars_at(start).peekable();
2577
2578        let scope = self.language_scope_at(start);
2579        let kind = |c| char_kind(&scope, c);
2580        let word_kind = cmp::max(
2581            prev_chars.peek().copied().map(kind),
2582            next_chars.peek().copied().map(kind),
2583        );
2584
2585        for ch in prev_chars {
2586            if Some(kind(ch)) == word_kind && ch != '\n' {
2587                start -= ch.len_utf8();
2588            } else {
2589                break;
2590            }
2591        }
2592
2593        for ch in next_chars {
2594            if Some(kind(ch)) == word_kind && ch != '\n' {
2595                end += ch.len_utf8();
2596            } else {
2597                break;
2598            }
2599        }
2600
2601        (start..end, word_kind)
2602    }
2603
2604    /// Returns the range for the closes syntax node enclosing the given range.
2605    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2606        let range = range.start.to_offset(self)..range.end.to_offset(self);
2607        let mut result: Option<Range<usize>> = None;
2608        'outer: for layer in self.syntax.layers_for_range(range.clone(), &self.text) {
2609            let mut cursor = layer.node().walk();
2610
2611            // Descend to the first leaf that touches the start of the range,
2612            // and if the range is non-empty, extends beyond the start.
2613            while cursor.goto_first_child_for_byte(range.start).is_some() {
2614                if !range.is_empty() && cursor.node().end_byte() == range.start {
2615                    cursor.goto_next_sibling();
2616                }
2617            }
2618
2619            // Ascend to the smallest ancestor that strictly contains the range.
2620            loop {
2621                let node_range = cursor.node().byte_range();
2622                if node_range.start <= range.start
2623                    && node_range.end >= range.end
2624                    && node_range.len() > range.len()
2625                {
2626                    break;
2627                }
2628                if !cursor.goto_parent() {
2629                    continue 'outer;
2630                }
2631            }
2632
2633            let left_node = cursor.node();
2634            let mut layer_result = left_node.byte_range();
2635
2636            // For an empty range, try to find another node immediately to the right of the range.
2637            if left_node.end_byte() == range.start {
2638                let mut right_node = None;
2639                while !cursor.goto_next_sibling() {
2640                    if !cursor.goto_parent() {
2641                        break;
2642                    }
2643                }
2644
2645                while cursor.node().start_byte() == range.start {
2646                    right_node = Some(cursor.node());
2647                    if !cursor.goto_first_child() {
2648                        break;
2649                    }
2650                }
2651
2652                // If there is a candidate node on both sides of the (empty) range, then
2653                // decide between the two by favoring a named node over an anonymous token.
2654                // If both nodes are the same in that regard, favor the right one.
2655                if let Some(right_node) = right_node {
2656                    if right_node.is_named() || !left_node.is_named() {
2657                        layer_result = right_node.byte_range();
2658                    }
2659                }
2660            }
2661
2662            if let Some(previous_result) = &result {
2663                if previous_result.len() < layer_result.len() {
2664                    continue;
2665                }
2666            }
2667            result = Some(layer_result);
2668        }
2669
2670        result
2671    }
2672
2673    /// Returns the outline for the buffer.
2674    ///
2675    /// This method allows passing an optional [SyntaxTheme] to
2676    /// syntax-highlight the returned symbols.
2677    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2678        self.outline_items_containing(0..self.len(), true, theme)
2679            .map(Outline::new)
2680    }
2681
2682    /// Returns all the symbols that contain the given position.
2683    ///
2684    /// This method allows passing an optional [SyntaxTheme] to
2685    /// syntax-highlight the returned symbols.
2686    pub fn symbols_containing<T: ToOffset>(
2687        &self,
2688        position: T,
2689        theme: Option<&SyntaxTheme>,
2690    ) -> Option<Vec<OutlineItem<Anchor>>> {
2691        let position = position.to_offset(self);
2692        let mut items = self.outline_items_containing(
2693            position.saturating_sub(1)..self.len().min(position + 1),
2694            false,
2695            theme,
2696        )?;
2697        let mut prev_depth = None;
2698        items.retain(|item| {
2699            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
2700            prev_depth = Some(item.depth);
2701            result
2702        });
2703        Some(items)
2704    }
2705
2706    fn outline_items_containing(
2707        &self,
2708        range: Range<usize>,
2709        include_extra_context: bool,
2710        theme: Option<&SyntaxTheme>,
2711    ) -> Option<Vec<OutlineItem<Anchor>>> {
2712        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2713            grammar.outline_config.as_ref().map(|c| &c.query)
2714        });
2715        let configs = matches
2716            .grammars()
2717            .iter()
2718            .map(|g| g.outline_config.as_ref().unwrap())
2719            .collect::<Vec<_>>();
2720
2721        let mut stack = Vec::<Range<usize>>::new();
2722        let mut items = Vec::new();
2723        while let Some(mat) = matches.peek() {
2724            let config = &configs[mat.grammar_index];
2725            let item_node = mat.captures.iter().find_map(|cap| {
2726                if cap.index == config.item_capture_ix {
2727                    Some(cap.node)
2728                } else {
2729                    None
2730                }
2731            })?;
2732
2733            let item_range = item_node.byte_range();
2734            if item_range.end < range.start || item_range.start > range.end {
2735                matches.advance();
2736                continue;
2737            }
2738
2739            let mut buffer_ranges = Vec::new();
2740            for capture in mat.captures {
2741                let node_is_name;
2742                if capture.index == config.name_capture_ix {
2743                    node_is_name = true;
2744                } else if Some(capture.index) == config.context_capture_ix
2745                    || (Some(capture.index) == config.extra_context_capture_ix
2746                        && include_extra_context)
2747                {
2748                    node_is_name = false;
2749                } else {
2750                    continue;
2751                }
2752
2753                let mut range = capture.node.start_byte()..capture.node.end_byte();
2754                let start = capture.node.start_position();
2755                if capture.node.end_position().row > start.row {
2756                    range.end =
2757                        range.start + self.line_len(start.row as u32) as usize - start.column;
2758                }
2759
2760                if !range.is_empty() {
2761                    buffer_ranges.push((range, node_is_name));
2762                }
2763            }
2764
2765            if buffer_ranges.is_empty() {
2766                matches.advance();
2767                continue;
2768            }
2769
2770            let mut text = String::new();
2771            let mut highlight_ranges = Vec::new();
2772            let mut name_ranges = Vec::new();
2773            let mut chunks = self.chunks(
2774                buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
2775                true,
2776            );
2777            let mut last_buffer_range_end = 0;
2778            for (buffer_range, is_name) in buffer_ranges {
2779                if !text.is_empty() && buffer_range.start > last_buffer_range_end {
2780                    text.push(' ');
2781                }
2782                last_buffer_range_end = buffer_range.end;
2783                if is_name {
2784                    let mut start = text.len();
2785                    let end = start + buffer_range.len();
2786
2787                    // When multiple names are captured, then the matcheable text
2788                    // includes the whitespace in between the names.
2789                    if !name_ranges.is_empty() {
2790                        start -= 1;
2791                    }
2792
2793                    name_ranges.push(start..end);
2794                }
2795
2796                let mut offset = buffer_range.start;
2797                chunks.seek(offset);
2798                for mut chunk in chunks.by_ref() {
2799                    if chunk.text.len() > buffer_range.end - offset {
2800                        chunk.text = &chunk.text[0..(buffer_range.end - offset)];
2801                        offset = buffer_range.end;
2802                    } else {
2803                        offset += chunk.text.len();
2804                    }
2805                    let style = chunk
2806                        .syntax_highlight_id
2807                        .zip(theme)
2808                        .and_then(|(highlight, theme)| highlight.style(theme));
2809                    if let Some(style) = style {
2810                        let start = text.len();
2811                        let end = start + chunk.text.len();
2812                        highlight_ranges.push((start..end, style));
2813                    }
2814                    text.push_str(chunk.text);
2815                    if offset >= buffer_range.end {
2816                        break;
2817                    }
2818                }
2819            }
2820
2821            matches.advance();
2822            while stack.last().map_or(false, |prev_range| {
2823                prev_range.start > item_range.start || prev_range.end < item_range.end
2824            }) {
2825                stack.pop();
2826            }
2827            stack.push(item_range.clone());
2828
2829            items.push(OutlineItem {
2830                depth: stack.len() - 1,
2831                range: self.anchor_after(item_range.start)..self.anchor_before(item_range.end),
2832                text,
2833                highlight_ranges,
2834                name_ranges,
2835            })
2836        }
2837        Some(items)
2838    }
2839
2840    /// For each grammar in the language, runs the provided
2841    /// [tree_sitter::Query] against the given range.
2842    pub fn matches(
2843        &self,
2844        range: Range<usize>,
2845        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
2846    ) -> SyntaxMapMatches {
2847        self.syntax.matches(range, self, query)
2848    }
2849
2850    /// Returns bracket range pairs overlapping or adjacent to `range`
2851    pub fn bracket_ranges<T: ToOffset>(
2852        &self,
2853        range: Range<T>,
2854    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
2855        // Find bracket pairs that *inclusively* contain the given range.
2856        let range = range.start.to_offset(self).saturating_sub(1)
2857            ..self.len().min(range.end.to_offset(self) + 1);
2858
2859        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2860            grammar.brackets_config.as_ref().map(|c| &c.query)
2861        });
2862        let configs = matches
2863            .grammars()
2864            .iter()
2865            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
2866            .collect::<Vec<_>>();
2867
2868        iter::from_fn(move || {
2869            while let Some(mat) = matches.peek() {
2870                let mut open = None;
2871                let mut close = None;
2872                let config = &configs[mat.grammar_index];
2873                for capture in mat.captures {
2874                    if capture.index == config.open_capture_ix {
2875                        open = Some(capture.node.byte_range());
2876                    } else if capture.index == config.close_capture_ix {
2877                        close = Some(capture.node.byte_range());
2878                    }
2879                }
2880
2881                matches.advance();
2882
2883                let Some((open, close)) = open.zip(close) else {
2884                    continue;
2885                };
2886
2887                let bracket_range = open.start..=close.end;
2888                if !bracket_range.overlaps(&range) {
2889                    continue;
2890                }
2891
2892                return Some((open, close));
2893            }
2894            None
2895        })
2896    }
2897
2898    /// Returns enclosing bracket ranges containing the given range
2899    pub fn enclosing_bracket_ranges<T: ToOffset>(
2900        &self,
2901        range: Range<T>,
2902    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
2903        let range = range.start.to_offset(self)..range.end.to_offset(self);
2904
2905        self.bracket_ranges(range.clone())
2906            .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
2907    }
2908
2909    /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
2910    ///
2911    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
2912    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
2913        &self,
2914        range: Range<T>,
2915        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
2916    ) -> Option<(Range<usize>, Range<usize>)> {
2917        let range = range.start.to_offset(self)..range.end.to_offset(self);
2918
2919        // Get the ranges of the innermost pair of brackets.
2920        let mut result: Option<(Range<usize>, Range<usize>)> = None;
2921
2922        for (open, close) in self.enclosing_bracket_ranges(range.clone()) {
2923            if let Some(range_filter) = range_filter {
2924                if !range_filter(open.clone(), close.clone()) {
2925                    continue;
2926                }
2927            }
2928
2929            let len = close.end - open.start;
2930
2931            if let Some((existing_open, existing_close)) = &result {
2932                let existing_len = existing_close.end - existing_open.start;
2933                if len > existing_len {
2934                    continue;
2935                }
2936            }
2937
2938            result = Some((open, close));
2939        }
2940
2941        result
2942    }
2943
2944    /// Returns anchor ranges for any matches of the redaction query.
2945    /// The buffer can be associated with multiple languages, and the redaction query associated with each
2946    /// will be run on the relevant section of the buffer.
2947    pub fn redacted_ranges<T: ToOffset>(
2948        &self,
2949        range: Range<T>,
2950    ) -> impl Iterator<Item = Range<usize>> + '_ {
2951        let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
2952        let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
2953            grammar
2954                .redactions_config
2955                .as_ref()
2956                .map(|config| &config.query)
2957        });
2958
2959        let configs = syntax_matches
2960            .grammars()
2961            .iter()
2962            .map(|grammar| grammar.redactions_config.as_ref())
2963            .collect::<Vec<_>>();
2964
2965        iter::from_fn(move || {
2966            let redacted_range = syntax_matches
2967                .peek()
2968                .and_then(|mat| {
2969                    configs[mat.grammar_index].and_then(|config| {
2970                        mat.captures
2971                            .iter()
2972                            .find(|capture| capture.index == config.redaction_capture_ix)
2973                    })
2974                })
2975                .map(|mat| mat.node.byte_range());
2976            syntax_matches.advance();
2977            redacted_range
2978        })
2979    }
2980
2981    /// Returns selections for remote peers intersecting the given range.
2982    #[allow(clippy::type_complexity)]
2983    pub fn remote_selections_in_range(
2984        &self,
2985        range: Range<Anchor>,
2986    ) -> impl Iterator<
2987        Item = (
2988            ReplicaId,
2989            bool,
2990            CursorShape,
2991            impl Iterator<Item = &Selection<Anchor>> + '_,
2992        ),
2993    > + '_ {
2994        self.remote_selections
2995            .iter()
2996            .filter(|(replica_id, set)| {
2997                **replica_id != self.text.replica_id() && !set.selections.is_empty()
2998            })
2999            .map(move |(replica_id, set)| {
3000                let start_ix = match set.selections.binary_search_by(|probe| {
3001                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
3002                }) {
3003                    Ok(ix) | Err(ix) => ix,
3004                };
3005                let end_ix = match set.selections.binary_search_by(|probe| {
3006                    probe.start.cmp(&range.end, self).then(Ordering::Less)
3007                }) {
3008                    Ok(ix) | Err(ix) => ix,
3009                };
3010
3011                (
3012                    *replica_id,
3013                    set.line_mode,
3014                    set.cursor_shape,
3015                    set.selections[start_ix..end_ix].iter(),
3016                )
3017            })
3018    }
3019
3020    /// Whether the buffer contains any git changes.
3021    pub fn has_git_diff(&self) -> bool {
3022        !self.git_diff.is_empty()
3023    }
3024
3025    /// Returns all the Git diff hunks intersecting the given
3026    /// row range.
3027    pub fn git_diff_hunks_in_row_range(
3028        &self,
3029        range: Range<u32>,
3030    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3031        self.git_diff.hunks_in_row_range(range, self)
3032    }
3033
3034    /// Returns all the Git diff hunks intersecting the given
3035    /// range.
3036    pub fn git_diff_hunks_intersecting_range(
3037        &self,
3038        range: Range<Anchor>,
3039    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3040        self.git_diff.hunks_intersecting_range(range, self)
3041    }
3042
3043    /// Returns all the Git diff hunks intersecting the given
3044    /// range, in reverse order.
3045    pub fn git_diff_hunks_intersecting_range_rev(
3046        &self,
3047        range: Range<Anchor>,
3048    ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3049        self.git_diff.hunks_intersecting_range_rev(range, self)
3050    }
3051
3052    /// Returns if the buffer contains any diagnostics.
3053    pub fn has_diagnostics(&self) -> bool {
3054        !self.diagnostics.is_empty()
3055    }
3056
3057    /// Returns all the diagnostics intersecting the given range.
3058    pub fn diagnostics_in_range<'a, T, O>(
3059        &'a self,
3060        search_range: Range<T>,
3061        reversed: bool,
3062    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3063    where
3064        T: 'a + Clone + ToOffset,
3065        O: 'a + FromAnchor + Ord,
3066    {
3067        let mut iterators: Vec<_> = self
3068            .diagnostics
3069            .iter()
3070            .map(|(_, collection)| {
3071                collection
3072                    .range::<T, O>(search_range.clone(), self, true, reversed)
3073                    .peekable()
3074            })
3075            .collect();
3076
3077        std::iter::from_fn(move || {
3078            let (next_ix, _) = iterators
3079                .iter_mut()
3080                .enumerate()
3081                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
3082                .min_by(|(_, a), (_, b)| a.range.start.cmp(&b.range.start))?;
3083            iterators[next_ix].next()
3084        })
3085    }
3086
3087    /// Returns all the diagnostic groups associated with the given
3088    /// language server id. If no language server id is provided,
3089    /// all diagnostics groups are returned.
3090    pub fn diagnostic_groups(
3091        &self,
3092        language_server_id: Option<LanguageServerId>,
3093    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
3094        let mut groups = Vec::new();
3095
3096        if let Some(language_server_id) = language_server_id {
3097            if let Ok(ix) = self
3098                .diagnostics
3099                .binary_search_by_key(&language_server_id, |e| e.0)
3100            {
3101                self.diagnostics[ix]
3102                    .1
3103                    .groups(language_server_id, &mut groups, self);
3104            }
3105        } else {
3106            for (language_server_id, diagnostics) in self.diagnostics.iter() {
3107                diagnostics.groups(*language_server_id, &mut groups, self);
3108            }
3109        }
3110
3111        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
3112            let a_start = &group_a.entries[group_a.primary_ix].range.start;
3113            let b_start = &group_b.entries[group_b.primary_ix].range.start;
3114            a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
3115        });
3116
3117        groups
3118    }
3119
3120    /// Returns an iterator over the diagnostics for the given group.
3121    pub fn diagnostic_group<'a, O>(
3122        &'a self,
3123        group_id: usize,
3124    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3125    where
3126        O: 'a + FromAnchor,
3127    {
3128        self.diagnostics
3129            .iter()
3130            .flat_map(move |(_, set)| set.group(group_id, self))
3131    }
3132
3133    /// The number of times diagnostics were updated.
3134    pub fn diagnostics_update_count(&self) -> usize {
3135        self.diagnostics_update_count
3136    }
3137
3138    /// The number of times the buffer was parsed.
3139    pub fn parse_count(&self) -> usize {
3140        self.parse_count
3141    }
3142
3143    /// The number of times selections were updated.
3144    pub fn selections_update_count(&self) -> usize {
3145        self.selections_update_count
3146    }
3147
3148    /// Returns a snapshot of underlying file.
3149    pub fn file(&self) -> Option<&Arc<dyn File>> {
3150        self.file.as_ref()
3151    }
3152
3153    /// Resolves the file path (relative to the worktree root) associated with the underlying file.
3154    pub fn resolve_file_path(&self, cx: &AppContext, include_root: bool) -> Option<PathBuf> {
3155        if let Some(file) = self.file() {
3156            if file.path().file_name().is_none() || include_root {
3157                Some(file.full_path(cx))
3158            } else {
3159                Some(file.path().to_path_buf())
3160            }
3161        } else {
3162            None
3163        }
3164    }
3165
3166    /// The number of times the underlying file was updated.
3167    pub fn file_update_count(&self) -> usize {
3168        self.file_update_count
3169    }
3170
3171    /// The number of times the git diff status was updated.
3172    pub fn git_diff_update_count(&self) -> usize {
3173        self.git_diff_update_count
3174    }
3175}
3176
3177fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
3178    indent_size_for_text(text.chars_at(Point::new(row, 0)))
3179}
3180
3181fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
3182    let mut result = IndentSize::spaces(0);
3183    for c in text {
3184        let kind = match c {
3185            ' ' => IndentKind::Space,
3186            '\t' => IndentKind::Tab,
3187            _ => break,
3188        };
3189        if result.len == 0 {
3190            result.kind = kind;
3191        }
3192        result.len += 1;
3193    }
3194    result
3195}
3196
3197impl Clone for BufferSnapshot {
3198    fn clone(&self) -> Self {
3199        Self {
3200            text: self.text.clone(),
3201            git_diff: self.git_diff.clone(),
3202            syntax: self.syntax.clone(),
3203            file: self.file.clone(),
3204            remote_selections: self.remote_selections.clone(),
3205            diagnostics: self.diagnostics.clone(),
3206            selections_update_count: self.selections_update_count,
3207            diagnostics_update_count: self.diagnostics_update_count,
3208            file_update_count: self.file_update_count,
3209            git_diff_update_count: self.git_diff_update_count,
3210            language: self.language.clone(),
3211            parse_count: self.parse_count,
3212        }
3213    }
3214}
3215
3216impl Deref for BufferSnapshot {
3217    type Target = text::BufferSnapshot;
3218
3219    fn deref(&self) -> &Self::Target {
3220        &self.text
3221    }
3222}
3223
3224unsafe impl<'a> Send for BufferChunks<'a> {}
3225
3226impl<'a> BufferChunks<'a> {
3227    pub(crate) fn new(
3228        text: &'a Rope,
3229        range: Range<usize>,
3230        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
3231        diagnostic_endpoints: Vec<DiagnosticEndpoint>,
3232    ) -> Self {
3233        let mut highlights = None;
3234        if let Some((captures, highlight_maps)) = syntax {
3235            highlights = Some(BufferChunkHighlights {
3236                captures,
3237                next_capture: None,
3238                stack: Default::default(),
3239                highlight_maps,
3240            })
3241        }
3242
3243        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
3244        let chunks = text.chunks_in_range(range.clone());
3245
3246        BufferChunks {
3247            range,
3248            chunks,
3249            diagnostic_endpoints,
3250            error_depth: 0,
3251            warning_depth: 0,
3252            information_depth: 0,
3253            hint_depth: 0,
3254            unnecessary_depth: 0,
3255            highlights,
3256        }
3257    }
3258
3259    /// Seeks to the given byte offset in the buffer.
3260    pub fn seek(&mut self, offset: usize) {
3261        self.range.start = offset;
3262        self.chunks.seek(self.range.start);
3263        if let Some(highlights) = self.highlights.as_mut() {
3264            highlights
3265                .stack
3266                .retain(|(end_offset, _)| *end_offset > offset);
3267            if let Some(capture) = &highlights.next_capture {
3268                if offset >= capture.node.start_byte() {
3269                    let next_capture_end = capture.node.end_byte();
3270                    if offset < next_capture_end {
3271                        highlights.stack.push((
3272                            next_capture_end,
3273                            highlights.highlight_maps[capture.grammar_index].get(capture.index),
3274                        ));
3275                    }
3276                    highlights.next_capture.take();
3277                }
3278            }
3279            highlights.captures.set_byte_range(self.range.clone());
3280        }
3281    }
3282
3283    /// The current byte offset in the buffer.
3284    pub fn offset(&self) -> usize {
3285        self.range.start
3286    }
3287
3288    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
3289        let depth = match endpoint.severity {
3290            DiagnosticSeverity::ERROR => &mut self.error_depth,
3291            DiagnosticSeverity::WARNING => &mut self.warning_depth,
3292            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
3293            DiagnosticSeverity::HINT => &mut self.hint_depth,
3294            _ => return,
3295        };
3296        if endpoint.is_start {
3297            *depth += 1;
3298        } else {
3299            *depth -= 1;
3300        }
3301
3302        if endpoint.is_unnecessary {
3303            if endpoint.is_start {
3304                self.unnecessary_depth += 1;
3305            } else {
3306                self.unnecessary_depth -= 1;
3307            }
3308        }
3309    }
3310
3311    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
3312        if self.error_depth > 0 {
3313            Some(DiagnosticSeverity::ERROR)
3314        } else if self.warning_depth > 0 {
3315            Some(DiagnosticSeverity::WARNING)
3316        } else if self.information_depth > 0 {
3317            Some(DiagnosticSeverity::INFORMATION)
3318        } else if self.hint_depth > 0 {
3319            Some(DiagnosticSeverity::HINT)
3320        } else {
3321            None
3322        }
3323    }
3324
3325    fn current_code_is_unnecessary(&self) -> bool {
3326        self.unnecessary_depth > 0
3327    }
3328}
3329
3330impl<'a> Iterator for BufferChunks<'a> {
3331    type Item = Chunk<'a>;
3332
3333    fn next(&mut self) -> Option<Self::Item> {
3334        let mut next_capture_start = usize::MAX;
3335        let mut next_diagnostic_endpoint = usize::MAX;
3336
3337        if let Some(highlights) = self.highlights.as_mut() {
3338            while let Some((parent_capture_end, _)) = highlights.stack.last() {
3339                if *parent_capture_end <= self.range.start {
3340                    highlights.stack.pop();
3341                } else {
3342                    break;
3343                }
3344            }
3345
3346            if highlights.next_capture.is_none() {
3347                highlights.next_capture = highlights.captures.next();
3348            }
3349
3350            while let Some(capture) = highlights.next_capture.as_ref() {
3351                if self.range.start < capture.node.start_byte() {
3352                    next_capture_start = capture.node.start_byte();
3353                    break;
3354                } else {
3355                    let highlight_id =
3356                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
3357                    highlights
3358                        .stack
3359                        .push((capture.node.end_byte(), highlight_id));
3360                    highlights.next_capture = highlights.captures.next();
3361                }
3362            }
3363        }
3364
3365        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
3366            if endpoint.offset <= self.range.start {
3367                self.update_diagnostic_depths(endpoint);
3368                self.diagnostic_endpoints.next();
3369            } else {
3370                next_diagnostic_endpoint = endpoint.offset;
3371                break;
3372            }
3373        }
3374
3375        if let Some(chunk) = self.chunks.peek() {
3376            let chunk_start = self.range.start;
3377            let mut chunk_end = (self.chunks.offset() + chunk.len())
3378                .min(next_capture_start)
3379                .min(next_diagnostic_endpoint);
3380            let mut highlight_id = None;
3381            if let Some(highlights) = self.highlights.as_ref() {
3382                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
3383                    chunk_end = chunk_end.min(*parent_capture_end);
3384                    highlight_id = Some(*parent_highlight_id);
3385                }
3386            }
3387
3388            let slice =
3389                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
3390            self.range.start = chunk_end;
3391            if self.range.start == self.chunks.offset() + chunk.len() {
3392                self.chunks.next().unwrap();
3393            }
3394
3395            Some(Chunk {
3396                text: slice,
3397                syntax_highlight_id: highlight_id,
3398                diagnostic_severity: self.current_diagnostic_severity(),
3399                is_unnecessary: self.current_code_is_unnecessary(),
3400                ..Default::default()
3401            })
3402        } else {
3403            None
3404        }
3405    }
3406}
3407
3408impl operation_queue::Operation for Operation {
3409    fn lamport_timestamp(&self) -> clock::Lamport {
3410        match self {
3411            Operation::Buffer(_) => {
3412                unreachable!("buffer operations should never be deferred at this layer")
3413            }
3414            Operation::UpdateDiagnostics {
3415                lamport_timestamp, ..
3416            }
3417            | Operation::UpdateSelections {
3418                lamport_timestamp, ..
3419            }
3420            | Operation::UpdateCompletionTriggers {
3421                lamport_timestamp, ..
3422            } => *lamport_timestamp,
3423        }
3424    }
3425}
3426
3427impl Default for Diagnostic {
3428    fn default() -> Self {
3429        Self {
3430            source: Default::default(),
3431            code: None,
3432            severity: DiagnosticSeverity::ERROR,
3433            message: Default::default(),
3434            group_id: 0,
3435            is_primary: false,
3436            is_disk_based: false,
3437            is_unnecessary: false,
3438        }
3439    }
3440}
3441
3442impl IndentSize {
3443    /// Returns an [IndentSize] representing the given spaces.
3444    pub fn spaces(len: u32) -> Self {
3445        Self {
3446            len,
3447            kind: IndentKind::Space,
3448        }
3449    }
3450
3451    /// Returns an [IndentSize] representing a tab.
3452    pub fn tab() -> Self {
3453        Self {
3454            len: 1,
3455            kind: IndentKind::Tab,
3456        }
3457    }
3458
3459    /// An iterator over the characters represented by this [IndentSize].
3460    pub fn chars(&self) -> impl Iterator<Item = char> {
3461        iter::repeat(self.char()).take(self.len as usize)
3462    }
3463
3464    /// The character representation of this [IndentSize].
3465    pub fn char(&self) -> char {
3466        match self.kind {
3467            IndentKind::Space => ' ',
3468            IndentKind::Tab => '\t',
3469        }
3470    }
3471
3472    /// Consumes the current [IndentSize] and returns a new one that has
3473    /// been shrunk or enlarged by the given size along the given direction.
3474    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
3475        match direction {
3476            Ordering::Less => {
3477                if self.kind == size.kind && self.len >= size.len {
3478                    self.len -= size.len;
3479                }
3480            }
3481            Ordering::Equal => {}
3482            Ordering::Greater => {
3483                if self.len == 0 {
3484                    self = size;
3485                } else if self.kind == size.kind {
3486                    self.len += size.len;
3487                }
3488            }
3489        }
3490        self
3491    }
3492}
3493
3494#[cfg(any(test, feature = "test-support"))]
3495pub struct TestFile {
3496    pub path: Arc<Path>,
3497    pub root_name: String,
3498}
3499
3500#[cfg(any(test, feature = "test-support"))]
3501impl File for TestFile {
3502    fn path(&self) -> &Arc<Path> {
3503        &self.path
3504    }
3505
3506    fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
3507        PathBuf::from(&self.root_name).join(self.path.as_ref())
3508    }
3509
3510    fn as_local(&self) -> Option<&dyn LocalFile> {
3511        None
3512    }
3513
3514    fn mtime(&self) -> Option<SystemTime> {
3515        unimplemented!()
3516    }
3517
3518    fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
3519        self.path().file_name().unwrap_or(self.root_name.as_ref())
3520    }
3521
3522    fn worktree_id(&self) -> usize {
3523        0
3524    }
3525
3526    fn is_deleted(&self) -> bool {
3527        unimplemented!()
3528    }
3529
3530    fn as_any(&self) -> &dyn std::any::Any {
3531        unimplemented!()
3532    }
3533
3534    fn to_proto(&self) -> rpc::proto::File {
3535        unimplemented!()
3536    }
3537
3538    fn is_private(&self) -> bool {
3539        false
3540    }
3541}
3542
3543pub(crate) fn contiguous_ranges(
3544    values: impl Iterator<Item = u32>,
3545    max_len: usize,
3546) -> impl Iterator<Item = Range<u32>> {
3547    let mut values = values;
3548    let mut current_range: Option<Range<u32>> = None;
3549    std::iter::from_fn(move || loop {
3550        if let Some(value) = values.next() {
3551            if let Some(range) = &mut current_range {
3552                if value == range.end && range.len() < max_len {
3553                    range.end += 1;
3554                    continue;
3555                }
3556            }
3557
3558            let prev_range = current_range.clone();
3559            current_range = Some(value..(value + 1));
3560            if prev_range.is_some() {
3561                return prev_range;
3562            }
3563        } else {
3564            return current_range.take();
3565        }
3566    })
3567}
3568
3569/// Returns the [CharKind] for the given character. When a scope is provided,
3570/// the function checks if the character is considered a word character
3571/// based on the language scope's word character settings.
3572pub fn char_kind(scope: &Option<LanguageScope>, c: char) -> CharKind {
3573    if c.is_whitespace() {
3574        return CharKind::Whitespace;
3575    } else if c.is_alphanumeric() || c == '_' {
3576        return CharKind::Word;
3577    }
3578
3579    if let Some(scope) = scope {
3580        if let Some(characters) = scope.word_characters() {
3581            if characters.contains(&c) {
3582                return CharKind::Word;
3583            }
3584        }
3585    }
3586
3587    CharKind::Punctuation
3588}
3589
3590/// Find all of the ranges of whitespace that occur at the ends of lines
3591/// in the given rope.
3592///
3593/// This could also be done with a regex search, but this implementation
3594/// avoids copying text.
3595pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
3596    let mut ranges = Vec::new();
3597
3598    let mut offset = 0;
3599    let mut prev_chunk_trailing_whitespace_range = 0..0;
3600    for chunk in rope.chunks() {
3601        let mut prev_line_trailing_whitespace_range = 0..0;
3602        for (i, line) in chunk.split('\n').enumerate() {
3603            let line_end_offset = offset + line.len();
3604            let trimmed_line_len = line.trim_end_matches(|c| matches!(c, ' ' | '\t')).len();
3605            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
3606
3607            if i == 0 && trimmed_line_len == 0 {
3608                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
3609            }
3610            if !prev_line_trailing_whitespace_range.is_empty() {
3611                ranges.push(prev_line_trailing_whitespace_range);
3612            }
3613
3614            offset = line_end_offset + 1;
3615            prev_line_trailing_whitespace_range = trailing_whitespace_range;
3616        }
3617
3618        offset -= 1;
3619        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
3620    }
3621
3622    if !prev_chunk_trailing_whitespace_range.is_empty() {
3623        ranges.push(prev_chunk_trailing_whitespace_range);
3624    }
3625
3626    ranges
3627}