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