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    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1924        let was_dirty = self.is_dirty();
1925        let old_version = self.version.clone();
1926
1927        if let Some((transaction_id, operation)) = self.text.redo() {
1928            self.send_operation(Operation::Buffer(operation), cx);
1929            self.did_edit(&old_version, was_dirty, cx);
1930            Some(transaction_id)
1931        } else {
1932            None
1933        }
1934    }
1935
1936    pub fn redo_to_transaction(
1937        &mut self,
1938        transaction_id: TransactionId,
1939        cx: &mut ModelContext<Self>,
1940    ) -> bool {
1941        let was_dirty = self.is_dirty();
1942        let old_version = self.version.clone();
1943
1944        let operations = self.text.redo_to_transaction(transaction_id);
1945        let redone = !operations.is_empty();
1946        for operation in operations {
1947            self.send_operation(Operation::Buffer(operation), cx);
1948        }
1949        if redone {
1950            self.did_edit(&old_version, was_dirty, cx)
1951        }
1952        redone
1953    }
1954
1955    pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
1956        self.completion_triggers = triggers.clone();
1957        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
1958        self.send_operation(
1959            Operation::UpdateCompletionTriggers {
1960                triggers,
1961                lamport_timestamp: self.completion_triggers_timestamp,
1962            },
1963            cx,
1964        );
1965        cx.notify();
1966    }
1967
1968    pub fn completion_triggers(&self) -> &[String] {
1969        &self.completion_triggers
1970    }
1971}
1972
1973#[cfg(any(test, feature = "test-support"))]
1974impl Buffer {
1975    pub fn edit_via_marked_text(
1976        &mut self,
1977        marked_string: &str,
1978        autoindent_mode: Option<AutoindentMode>,
1979        cx: &mut ModelContext<Self>,
1980    ) {
1981        let edits = self.edits_for_marked_text(marked_string);
1982        self.edit(edits, autoindent_mode, cx);
1983    }
1984
1985    pub fn set_group_interval(&mut self, group_interval: Duration) {
1986        self.text.set_group_interval(group_interval);
1987    }
1988
1989    pub fn randomly_edit<T>(
1990        &mut self,
1991        rng: &mut T,
1992        old_range_count: usize,
1993        cx: &mut ModelContext<Self>,
1994    ) where
1995        T: rand::Rng,
1996    {
1997        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
1998        let mut last_end = None;
1999        for _ in 0..old_range_count {
2000            if last_end.map_or(false, |last_end| last_end >= self.len()) {
2001                break;
2002            }
2003
2004            let new_start = last_end.map_or(0, |last_end| last_end + 1);
2005            let mut range = self.random_byte_range(new_start, rng);
2006            if rng.gen_bool(0.2) {
2007                mem::swap(&mut range.start, &mut range.end);
2008            }
2009            last_end = Some(range.end);
2010
2011            let new_text_len = rng.gen_range(0..10);
2012            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2013
2014            edits.push((range, new_text));
2015        }
2016        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2017        self.edit(edits, None, cx);
2018    }
2019
2020    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
2021        let was_dirty = self.is_dirty();
2022        let old_version = self.version.clone();
2023
2024        let ops = self.text.randomly_undo_redo(rng);
2025        if !ops.is_empty() {
2026            for op in ops {
2027                self.send_operation(Operation::Buffer(op), cx);
2028                self.did_edit(&old_version, was_dirty, cx);
2029            }
2030        }
2031    }
2032}
2033
2034impl EventEmitter<Event> for Buffer {}
2035
2036impl Deref for Buffer {
2037    type Target = TextBuffer;
2038
2039    fn deref(&self) -> &Self::Target {
2040        &self.text
2041    }
2042}
2043
2044impl BufferSnapshot {
2045    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2046        indent_size_for_line(self, row)
2047    }
2048
2049    pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &AppContext) -> IndentSize {
2050        let settings = language_settings(self.language_at(position), self.file(), cx);
2051        if settings.hard_tabs {
2052            IndentSize::tab()
2053        } else {
2054            IndentSize::spaces(settings.tab_size.get())
2055        }
2056    }
2057
2058    /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2059    /// is passed in as `single_indent_size`.
2060    pub fn suggested_indents(
2061        &self,
2062        rows: impl Iterator<Item = u32>,
2063        single_indent_size: IndentSize,
2064    ) -> BTreeMap<u32, IndentSize> {
2065        let mut result = BTreeMap::new();
2066
2067        for row_range in contiguous_ranges(rows, 10) {
2068            let suggestions = match self.suggest_autoindents(row_range.clone()) {
2069                Some(suggestions) => suggestions,
2070                _ => break,
2071            };
2072
2073            for (row, suggestion) in row_range.zip(suggestions) {
2074                let indent_size = if let Some(suggestion) = suggestion {
2075                    result
2076                        .get(&suggestion.basis_row)
2077                        .copied()
2078                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2079                        .with_delta(suggestion.delta, single_indent_size)
2080                } else {
2081                    self.indent_size_for_line(row)
2082                };
2083
2084                result.insert(row, indent_size);
2085            }
2086        }
2087
2088        result
2089    }
2090
2091    fn suggest_autoindents(
2092        &self,
2093        row_range: Range<u32>,
2094    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2095        let config = &self.language.as_ref()?.config;
2096        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2097
2098        // Find the suggested indentation ranges based on the syntax tree.
2099        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2100        let end = Point::new(row_range.end, 0);
2101        let range = (start..end).to_offset(&self.text);
2102        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2103            Some(&grammar.indents_config.as_ref()?.query)
2104        });
2105        let indent_configs = matches
2106            .grammars()
2107            .iter()
2108            .map(|grammar| grammar.indents_config.as_ref().unwrap())
2109            .collect::<Vec<_>>();
2110
2111        let mut indent_ranges = Vec::<Range<Point>>::new();
2112        let mut outdent_positions = Vec::<Point>::new();
2113        while let Some(mat) = matches.peek() {
2114            let mut start: Option<Point> = None;
2115            let mut end: Option<Point> = None;
2116
2117            let config = &indent_configs[mat.grammar_index];
2118            for capture in mat.captures {
2119                if capture.index == config.indent_capture_ix {
2120                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2121                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2122                } else if Some(capture.index) == config.start_capture_ix {
2123                    start = Some(Point::from_ts_point(capture.node.end_position()));
2124                } else if Some(capture.index) == config.end_capture_ix {
2125                    end = Some(Point::from_ts_point(capture.node.start_position()));
2126                } else if Some(capture.index) == config.outdent_capture_ix {
2127                    outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2128                }
2129            }
2130
2131            matches.advance();
2132            if let Some((start, end)) = start.zip(end) {
2133                if start.row == end.row {
2134                    continue;
2135                }
2136
2137                let range = start..end;
2138                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2139                    Err(ix) => indent_ranges.insert(ix, range),
2140                    Ok(ix) => {
2141                        let prev_range = &mut indent_ranges[ix];
2142                        prev_range.end = prev_range.end.max(range.end);
2143                    }
2144                }
2145            }
2146        }
2147
2148        let mut error_ranges = Vec::<Range<Point>>::new();
2149        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2150            Some(&grammar.error_query)
2151        });
2152        while let Some(mat) = matches.peek() {
2153            let node = mat.captures[0].node;
2154            let start = Point::from_ts_point(node.start_position());
2155            let end = Point::from_ts_point(node.end_position());
2156            let range = start..end;
2157            let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2158                Ok(ix) | Err(ix) => ix,
2159            };
2160            let mut end_ix = ix;
2161            while let Some(existing_range) = error_ranges.get(end_ix) {
2162                if existing_range.end < end {
2163                    end_ix += 1;
2164                } else {
2165                    break;
2166                }
2167            }
2168            error_ranges.splice(ix..end_ix, [range]);
2169            matches.advance();
2170        }
2171
2172        outdent_positions.sort();
2173        for outdent_position in outdent_positions {
2174            // find the innermost indent range containing this outdent_position
2175            // set its end to the outdent position
2176            if let Some(range_to_truncate) = indent_ranges
2177                .iter_mut()
2178                .filter(|indent_range| indent_range.contains(&outdent_position))
2179                .last()
2180            {
2181                range_to_truncate.end = outdent_position;
2182            }
2183        }
2184
2185        // Find the suggested indentation increases and decreased based on regexes.
2186        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2187        self.for_each_line(
2188            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2189                ..Point::new(row_range.end, 0),
2190            |row, line| {
2191                if config
2192                    .decrease_indent_pattern
2193                    .as_ref()
2194                    .map_or(false, |regex| regex.is_match(line))
2195                {
2196                    indent_change_rows.push((row, Ordering::Less));
2197                }
2198                if config
2199                    .increase_indent_pattern
2200                    .as_ref()
2201                    .map_or(false, |regex| regex.is_match(line))
2202                {
2203                    indent_change_rows.push((row + 1, Ordering::Greater));
2204                }
2205            },
2206        );
2207
2208        let mut indent_changes = indent_change_rows.into_iter().peekable();
2209        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2210            prev_non_blank_row.unwrap_or(0)
2211        } else {
2212            row_range.start.saturating_sub(1)
2213        };
2214        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2215        Some(row_range.map(move |row| {
2216            let row_start = Point::new(row, self.indent_size_for_line(row).len);
2217
2218            let mut indent_from_prev_row = false;
2219            let mut outdent_from_prev_row = false;
2220            let mut outdent_to_row = u32::MAX;
2221
2222            while let Some((indent_row, delta)) = indent_changes.peek() {
2223                match indent_row.cmp(&row) {
2224                    Ordering::Equal => match delta {
2225                        Ordering::Less => outdent_from_prev_row = true,
2226                        Ordering::Greater => indent_from_prev_row = true,
2227                        _ => {}
2228                    },
2229
2230                    Ordering::Greater => break,
2231                    Ordering::Less => {}
2232                }
2233
2234                indent_changes.next();
2235            }
2236
2237            for range in &indent_ranges {
2238                if range.start.row >= row {
2239                    break;
2240                }
2241                if range.start.row == prev_row && range.end > row_start {
2242                    indent_from_prev_row = true;
2243                }
2244                if range.end > prev_row_start && range.end <= row_start {
2245                    outdent_to_row = outdent_to_row.min(range.start.row);
2246                }
2247            }
2248
2249            let within_error = error_ranges
2250                .iter()
2251                .any(|e| e.start.row < row && e.end > row_start);
2252
2253            let suggestion = if outdent_to_row == prev_row
2254                || (outdent_from_prev_row && indent_from_prev_row)
2255            {
2256                Some(IndentSuggestion {
2257                    basis_row: prev_row,
2258                    delta: Ordering::Equal,
2259                    within_error,
2260                })
2261            } else if indent_from_prev_row {
2262                Some(IndentSuggestion {
2263                    basis_row: prev_row,
2264                    delta: Ordering::Greater,
2265                    within_error,
2266                })
2267            } else if outdent_to_row < prev_row {
2268                Some(IndentSuggestion {
2269                    basis_row: outdent_to_row,
2270                    delta: Ordering::Equal,
2271                    within_error,
2272                })
2273            } else if outdent_from_prev_row {
2274                Some(IndentSuggestion {
2275                    basis_row: prev_row,
2276                    delta: Ordering::Less,
2277                    within_error,
2278                })
2279            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
2280            {
2281                Some(IndentSuggestion {
2282                    basis_row: prev_row,
2283                    delta: Ordering::Equal,
2284                    within_error,
2285                })
2286            } else {
2287                None
2288            };
2289
2290            prev_row = row;
2291            prev_row_start = row_start;
2292            suggestion
2293        }))
2294    }
2295
2296    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2297        while row > 0 {
2298            row -= 1;
2299            if !self.is_line_blank(row) {
2300                return Some(row);
2301            }
2302        }
2303        None
2304    }
2305
2306    /// Iterates over chunks of text in the given range of the buffer. Text is chunked
2307    /// in an arbitrary way due to being stored in a [`rope::Rope`]. The text is also
2308    /// returned in chunks where each chunk has a single syntax highlighting style and
2309    /// diagnostic status.
2310    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
2311        let range = range.start.to_offset(self)..range.end.to_offset(self);
2312
2313        let mut syntax = None;
2314        let mut diagnostic_endpoints = Vec::new();
2315        if language_aware {
2316            let captures = self.syntax.captures(range.clone(), &self.text, |grammar| {
2317                grammar.highlights_query.as_ref()
2318            });
2319            let highlight_maps = captures
2320                .grammars()
2321                .into_iter()
2322                .map(|grammar| grammar.highlight_map())
2323                .collect();
2324            syntax = Some((captures, highlight_maps));
2325            for entry in self.diagnostics_in_range::<_, usize>(range.clone(), false) {
2326                diagnostic_endpoints.push(DiagnosticEndpoint {
2327                    offset: entry.range.start,
2328                    is_start: true,
2329                    severity: entry.diagnostic.severity,
2330                    is_unnecessary: entry.diagnostic.is_unnecessary,
2331                });
2332                diagnostic_endpoints.push(DiagnosticEndpoint {
2333                    offset: entry.range.end,
2334                    is_start: false,
2335                    severity: entry.diagnostic.severity,
2336                    is_unnecessary: entry.diagnostic.is_unnecessary,
2337                });
2338            }
2339            diagnostic_endpoints
2340                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
2341        }
2342
2343        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostic_endpoints)
2344    }
2345
2346    /// Invokes the given callback for each line of text in the given range of the buffer.
2347    /// Uses callback to avoid allocating a string for each line.
2348    fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
2349        let mut line = String::new();
2350        let mut row = range.start.row;
2351        for chunk in self
2352            .as_rope()
2353            .chunks_in_range(range.to_offset(self))
2354            .chain(["\n"])
2355        {
2356            for (newline_ix, text) in chunk.split('\n').enumerate() {
2357                if newline_ix > 0 {
2358                    callback(row, &line);
2359                    row += 1;
2360                    line.clear();
2361                }
2362                line.push_str(text);
2363            }
2364        }
2365    }
2366
2367    /// Iterates over every [`SyntaxLayer`] in the buffer.
2368    pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
2369        self.syntax.layers_for_range(0..self.len(), &self.text)
2370    }
2371
2372    pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
2373        let offset = position.to_offset(self);
2374        self.syntax
2375            .layers_for_range(offset..offset, &self.text)
2376            .filter(|l| l.node().end_byte() > offset)
2377            .last()
2378    }
2379
2380    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
2381        self.syntax_layer_at(position)
2382            .map(|info| info.language)
2383            .or(self.language.as_ref())
2384    }
2385
2386    pub fn settings_at<'a, D: ToOffset>(
2387        &self,
2388        position: D,
2389        cx: &'a AppContext,
2390    ) -> &'a LanguageSettings {
2391        language_settings(self.language_at(position), self.file.as_ref(), cx)
2392    }
2393
2394    pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
2395        let offset = position.to_offset(self);
2396        let mut scope = None;
2397        let mut smallest_range: Option<Range<usize>> = None;
2398
2399        // Use the layer that has the smallest node intersecting the given point.
2400        for layer in self.syntax.layers_for_range(offset..offset, &self.text) {
2401            let mut cursor = layer.node().walk();
2402
2403            let mut range = None;
2404            loop {
2405                let child_range = cursor.node().byte_range();
2406                if !child_range.to_inclusive().contains(&offset) {
2407                    break;
2408                }
2409
2410                range = Some(child_range);
2411                if cursor.goto_first_child_for_byte(offset).is_none() {
2412                    break;
2413                }
2414            }
2415
2416            if let Some(range) = range {
2417                if smallest_range
2418                    .as_ref()
2419                    .map_or(true, |smallest_range| range.len() < smallest_range.len())
2420                {
2421                    smallest_range = Some(range);
2422                    scope = Some(LanguageScope {
2423                        language: layer.language.clone(),
2424                        override_id: layer.override_id(offset, &self.text),
2425                    });
2426                }
2427            }
2428        }
2429
2430        scope.or_else(|| {
2431            self.language.clone().map(|language| LanguageScope {
2432                language,
2433                override_id: None,
2434            })
2435        })
2436    }
2437
2438    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2439        let mut start = start.to_offset(self);
2440        let mut end = start;
2441        let mut next_chars = self.chars_at(start).peekable();
2442        let mut prev_chars = self.reversed_chars_at(start).peekable();
2443
2444        let scope = self.language_scope_at(start);
2445        let kind = |c| char_kind(&scope, c);
2446        let word_kind = cmp::max(
2447            prev_chars.peek().copied().map(kind),
2448            next_chars.peek().copied().map(kind),
2449        );
2450
2451        for ch in prev_chars {
2452            if Some(kind(ch)) == word_kind && ch != '\n' {
2453                start -= ch.len_utf8();
2454            } else {
2455                break;
2456            }
2457        }
2458
2459        for ch in next_chars {
2460            if Some(kind(ch)) == word_kind && ch != '\n' {
2461                end += ch.len_utf8();
2462            } else {
2463                break;
2464            }
2465        }
2466
2467        (start..end, word_kind)
2468    }
2469
2470    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2471        let range = range.start.to_offset(self)..range.end.to_offset(self);
2472        let mut result: Option<Range<usize>> = None;
2473        'outer: for layer in self.syntax.layers_for_range(range.clone(), &self.text) {
2474            let mut cursor = layer.node().walk();
2475
2476            // Descend to the first leaf that touches the start of the range,
2477            // and if the range is non-empty, extends beyond the start.
2478            while cursor.goto_first_child_for_byte(range.start).is_some() {
2479                if !range.is_empty() && cursor.node().end_byte() == range.start {
2480                    cursor.goto_next_sibling();
2481                }
2482            }
2483
2484            // Ascend to the smallest ancestor that strictly contains the range.
2485            loop {
2486                let node_range = cursor.node().byte_range();
2487                if node_range.start <= range.start
2488                    && node_range.end >= range.end
2489                    && node_range.len() > range.len()
2490                {
2491                    break;
2492                }
2493                if !cursor.goto_parent() {
2494                    continue 'outer;
2495                }
2496            }
2497
2498            let left_node = cursor.node();
2499            let mut layer_result = left_node.byte_range();
2500
2501            // For an empty range, try to find another node immediately to the right of the range.
2502            if left_node.end_byte() == range.start {
2503                let mut right_node = None;
2504                while !cursor.goto_next_sibling() {
2505                    if !cursor.goto_parent() {
2506                        break;
2507                    }
2508                }
2509
2510                while cursor.node().start_byte() == range.start {
2511                    right_node = Some(cursor.node());
2512                    if !cursor.goto_first_child() {
2513                        break;
2514                    }
2515                }
2516
2517                // If there is a candidate node on both sides of the (empty) range, then
2518                // decide between the two by favoring a named node over an anonymous token.
2519                // If both nodes are the same in that regard, favor the right one.
2520                if let Some(right_node) = right_node {
2521                    if right_node.is_named() || !left_node.is_named() {
2522                        layer_result = right_node.byte_range();
2523                    }
2524                }
2525            }
2526
2527            if let Some(previous_result) = &result {
2528                if previous_result.len() < layer_result.len() {
2529                    continue;
2530                }
2531            }
2532            result = Some(layer_result);
2533        }
2534
2535        result
2536    }
2537
2538    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2539        self.outline_items_containing(0..self.len(), true, theme)
2540            .map(Outline::new)
2541    }
2542
2543    pub fn symbols_containing<T: ToOffset>(
2544        &self,
2545        position: T,
2546        theme: Option<&SyntaxTheme>,
2547    ) -> Option<Vec<OutlineItem<Anchor>>> {
2548        let position = position.to_offset(self);
2549        let mut items = self.outline_items_containing(
2550            position.saturating_sub(1)..self.len().min(position + 1),
2551            false,
2552            theme,
2553        )?;
2554        let mut prev_depth = None;
2555        items.retain(|item| {
2556            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
2557            prev_depth = Some(item.depth);
2558            result
2559        });
2560        Some(items)
2561    }
2562
2563    fn outline_items_containing(
2564        &self,
2565        range: Range<usize>,
2566        include_extra_context: bool,
2567        theme: Option<&SyntaxTheme>,
2568    ) -> Option<Vec<OutlineItem<Anchor>>> {
2569        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2570            grammar.outline_config.as_ref().map(|c| &c.query)
2571        });
2572        let configs = matches
2573            .grammars()
2574            .iter()
2575            .map(|g| g.outline_config.as_ref().unwrap())
2576            .collect::<Vec<_>>();
2577
2578        let mut stack = Vec::<Range<usize>>::new();
2579        let mut items = Vec::new();
2580        while let Some(mat) = matches.peek() {
2581            let config = &configs[mat.grammar_index];
2582            let item_node = mat.captures.iter().find_map(|cap| {
2583                if cap.index == config.item_capture_ix {
2584                    Some(cap.node)
2585                } else {
2586                    None
2587                }
2588            })?;
2589
2590            let item_range = item_node.byte_range();
2591            if item_range.end < range.start || item_range.start > range.end {
2592                matches.advance();
2593                continue;
2594            }
2595
2596            let mut buffer_ranges = Vec::new();
2597            for capture in mat.captures {
2598                let node_is_name;
2599                if capture.index == config.name_capture_ix {
2600                    node_is_name = true;
2601                } else if Some(capture.index) == config.context_capture_ix
2602                    || (Some(capture.index) == config.extra_context_capture_ix
2603                        && include_extra_context)
2604                {
2605                    node_is_name = false;
2606                } else {
2607                    continue;
2608                }
2609
2610                let mut range = capture.node.start_byte()..capture.node.end_byte();
2611                let start = capture.node.start_position();
2612                if capture.node.end_position().row > start.row {
2613                    range.end =
2614                        range.start + self.line_len(start.row as u32) as usize - start.column;
2615                }
2616
2617                buffer_ranges.push((range, node_is_name));
2618            }
2619
2620            if buffer_ranges.is_empty() {
2621                continue;
2622            }
2623
2624            let mut text = String::new();
2625            let mut highlight_ranges = Vec::new();
2626            let mut name_ranges = Vec::new();
2627            let mut chunks = self.chunks(
2628                buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
2629                true,
2630            );
2631            let mut last_buffer_range_end = 0;
2632            for (buffer_range, is_name) in buffer_ranges {
2633                if !text.is_empty() && buffer_range.start > last_buffer_range_end {
2634                    text.push(' ');
2635                }
2636                last_buffer_range_end = buffer_range.end;
2637                if is_name {
2638                    let mut start = text.len();
2639                    let end = start + buffer_range.len();
2640
2641                    // When multiple names are captured, then the matcheable text
2642                    // includes the whitespace in between the names.
2643                    if !name_ranges.is_empty() {
2644                        start -= 1;
2645                    }
2646
2647                    name_ranges.push(start..end);
2648                }
2649
2650                let mut offset = buffer_range.start;
2651                chunks.seek(offset);
2652                for mut chunk in chunks.by_ref() {
2653                    if chunk.text.len() > buffer_range.end - offset {
2654                        chunk.text = &chunk.text[0..(buffer_range.end - offset)];
2655                        offset = buffer_range.end;
2656                    } else {
2657                        offset += chunk.text.len();
2658                    }
2659                    let style = chunk
2660                        .syntax_highlight_id
2661                        .zip(theme)
2662                        .and_then(|(highlight, theme)| highlight.style(theme));
2663                    if let Some(style) = style {
2664                        let start = text.len();
2665                        let end = start + chunk.text.len();
2666                        highlight_ranges.push((start..end, style));
2667                    }
2668                    text.push_str(chunk.text);
2669                    if offset >= buffer_range.end {
2670                        break;
2671                    }
2672                }
2673            }
2674
2675            matches.advance();
2676            while stack.last().map_or(false, |prev_range| {
2677                prev_range.start > item_range.start || prev_range.end < item_range.end
2678            }) {
2679                stack.pop();
2680            }
2681            stack.push(item_range.clone());
2682
2683            items.push(OutlineItem {
2684                depth: stack.len() - 1,
2685                range: self.anchor_after(item_range.start)..self.anchor_before(item_range.end),
2686                text,
2687                highlight_ranges,
2688                name_ranges,
2689            })
2690        }
2691        Some(items)
2692    }
2693
2694    pub fn matches(
2695        &self,
2696        range: Range<usize>,
2697        query: fn(&Grammar) -> Option<&tree_sitter::Query>,
2698    ) -> SyntaxMapMatches {
2699        self.syntax.matches(range, self, query)
2700    }
2701
2702    /// Returns bracket range pairs overlapping or adjacent to `range`
2703    pub fn bracket_ranges<'a, T: ToOffset>(
2704        &'a self,
2705        range: Range<T>,
2706    ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a {
2707        // Find bracket pairs that *inclusively* contain the given range.
2708        let range = range.start.to_offset(self).saturating_sub(1)
2709            ..self.len().min(range.end.to_offset(self) + 1);
2710
2711        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2712            grammar.brackets_config.as_ref().map(|c| &c.query)
2713        });
2714        let configs = matches
2715            .grammars()
2716            .iter()
2717            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
2718            .collect::<Vec<_>>();
2719
2720        iter::from_fn(move || {
2721            while let Some(mat) = matches.peek() {
2722                let mut open = None;
2723                let mut close = None;
2724                let config = &configs[mat.grammar_index];
2725                for capture in mat.captures {
2726                    if capture.index == config.open_capture_ix {
2727                        open = Some(capture.node.byte_range());
2728                    } else if capture.index == config.close_capture_ix {
2729                        close = Some(capture.node.byte_range());
2730                    }
2731                }
2732
2733                matches.advance();
2734
2735                let Some((open, close)) = open.zip(close) else {
2736                    continue;
2737                };
2738
2739                let bracket_range = open.start..=close.end;
2740                if !bracket_range.overlaps(&range) {
2741                    continue;
2742                }
2743
2744                return Some((open, close));
2745            }
2746            None
2747        })
2748    }
2749
2750    #[allow(clippy::type_complexity)]
2751    pub fn remote_selections_in_range(
2752        &self,
2753        range: Range<Anchor>,
2754    ) -> impl Iterator<
2755        Item = (
2756            ReplicaId,
2757            bool,
2758            CursorShape,
2759            impl Iterator<Item = &Selection<Anchor>> + '_,
2760        ),
2761    > + '_ {
2762        self.remote_selections
2763            .iter()
2764            .filter(|(replica_id, set)| {
2765                **replica_id != self.text.replica_id() && !set.selections.is_empty()
2766            })
2767            .map(move |(replica_id, set)| {
2768                let start_ix = match set.selections.binary_search_by(|probe| {
2769                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
2770                }) {
2771                    Ok(ix) | Err(ix) => ix,
2772                };
2773                let end_ix = match set.selections.binary_search_by(|probe| {
2774                    probe.start.cmp(&range.end, self).then(Ordering::Less)
2775                }) {
2776                    Ok(ix) | Err(ix) => ix,
2777                };
2778
2779                (
2780                    *replica_id,
2781                    set.line_mode,
2782                    set.cursor_shape,
2783                    set.selections[start_ix..end_ix].iter(),
2784                )
2785            })
2786    }
2787
2788    pub fn git_diff_hunks_in_row_range<'a>(
2789        &'a self,
2790        range: Range<u32>,
2791    ) -> impl 'a + Iterator<Item = git::diff::DiffHunk<u32>> {
2792        self.git_diff.hunks_in_row_range(range, self)
2793    }
2794
2795    pub fn git_diff_hunks_intersecting_range<'a>(
2796        &'a self,
2797        range: Range<Anchor>,
2798    ) -> impl 'a + Iterator<Item = git::diff::DiffHunk<u32>> {
2799        self.git_diff.hunks_intersecting_range(range, self)
2800    }
2801
2802    pub fn git_diff_hunks_intersecting_range_rev<'a>(
2803        &'a self,
2804        range: Range<Anchor>,
2805    ) -> impl 'a + Iterator<Item = git::diff::DiffHunk<u32>> {
2806        self.git_diff.hunks_intersecting_range_rev(range, self)
2807    }
2808
2809    pub fn diagnostics_in_range<'a, T, O>(
2810        &'a self,
2811        search_range: Range<T>,
2812        reversed: bool,
2813    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2814    where
2815        T: 'a + Clone + ToOffset,
2816        O: 'a + FromAnchor + Ord,
2817    {
2818        let mut iterators: Vec<_> = self
2819            .diagnostics
2820            .iter()
2821            .map(|(_, collection)| {
2822                collection
2823                    .range::<T, O>(search_range.clone(), self, true, reversed)
2824                    .peekable()
2825            })
2826            .collect();
2827
2828        std::iter::from_fn(move || {
2829            let (next_ix, _) = iterators
2830                .iter_mut()
2831                .enumerate()
2832                .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
2833                .min_by(|(_, a), (_, b)| a.range.start.cmp(&b.range.start))?;
2834            iterators[next_ix].next()
2835        })
2836    }
2837
2838    pub fn diagnostic_groups(
2839        &self,
2840        language_server_id: Option<LanguageServerId>,
2841    ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
2842        let mut groups = Vec::new();
2843
2844        if let Some(language_server_id) = language_server_id {
2845            if let Ok(ix) = self
2846                .diagnostics
2847                .binary_search_by_key(&language_server_id, |e| e.0)
2848            {
2849                self.diagnostics[ix]
2850                    .1
2851                    .groups(language_server_id, &mut groups, self);
2852            }
2853        } else {
2854            for (language_server_id, diagnostics) in self.diagnostics.iter() {
2855                diagnostics.groups(*language_server_id, &mut groups, self);
2856            }
2857        }
2858
2859        groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
2860            let a_start = &group_a.entries[group_a.primary_ix].range.start;
2861            let b_start = &group_b.entries[group_b.primary_ix].range.start;
2862            a_start.cmp(b_start, self).then_with(|| id_a.cmp(&id_b))
2863        });
2864
2865        groups
2866    }
2867
2868    pub fn diagnostic_group<'a, O>(
2869        &'a self,
2870        group_id: usize,
2871    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2872    where
2873        O: 'a + FromAnchor,
2874    {
2875        self.diagnostics
2876            .iter()
2877            .flat_map(move |(_, set)| set.group(group_id, self))
2878    }
2879
2880    pub fn diagnostics_update_count(&self) -> usize {
2881        self.diagnostics_update_count
2882    }
2883
2884    pub fn parse_count(&self) -> usize {
2885        self.parse_count
2886    }
2887
2888    pub fn selections_update_count(&self) -> usize {
2889        self.selections_update_count
2890    }
2891
2892    pub fn file(&self) -> Option<&Arc<dyn File>> {
2893        self.file.as_ref()
2894    }
2895
2896    pub fn resolve_file_path(&self, cx: &AppContext, include_root: bool) -> Option<PathBuf> {
2897        if let Some(file) = self.file() {
2898            if file.path().file_name().is_none() || include_root {
2899                Some(file.full_path(cx))
2900            } else {
2901                Some(file.path().to_path_buf())
2902            }
2903        } else {
2904            None
2905        }
2906    }
2907
2908    pub fn file_update_count(&self) -> usize {
2909        self.file_update_count
2910    }
2911
2912    pub fn git_diff_update_count(&self) -> usize {
2913        self.git_diff_update_count
2914    }
2915}
2916
2917fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
2918    indent_size_for_text(text.chars_at(Point::new(row, 0)))
2919}
2920
2921pub fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
2922    let mut result = IndentSize::spaces(0);
2923    for c in text {
2924        let kind = match c {
2925            ' ' => IndentKind::Space,
2926            '\t' => IndentKind::Tab,
2927            _ => break,
2928        };
2929        if result.len == 0 {
2930            result.kind = kind;
2931        }
2932        result.len += 1;
2933    }
2934    result
2935}
2936
2937impl Clone for BufferSnapshot {
2938    fn clone(&self) -> Self {
2939        Self {
2940            text: self.text.clone(),
2941            git_diff: self.git_diff.clone(),
2942            syntax: self.syntax.clone(),
2943            file: self.file.clone(),
2944            remote_selections: self.remote_selections.clone(),
2945            diagnostics: self.diagnostics.clone(),
2946            selections_update_count: self.selections_update_count,
2947            diagnostics_update_count: self.diagnostics_update_count,
2948            file_update_count: self.file_update_count,
2949            git_diff_update_count: self.git_diff_update_count,
2950            language: self.language.clone(),
2951            parse_count: self.parse_count,
2952        }
2953    }
2954}
2955
2956impl Deref for BufferSnapshot {
2957    type Target = text::BufferSnapshot;
2958
2959    fn deref(&self) -> &Self::Target {
2960        &self.text
2961    }
2962}
2963
2964unsafe impl<'a> Send for BufferChunks<'a> {}
2965
2966impl<'a> BufferChunks<'a> {
2967    pub(crate) fn new(
2968        text: &'a Rope,
2969        range: Range<usize>,
2970        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
2971        diagnostic_endpoints: Vec<DiagnosticEndpoint>,
2972    ) -> Self {
2973        let mut highlights = None;
2974        if let Some((captures, highlight_maps)) = syntax {
2975            highlights = Some(BufferChunkHighlights {
2976                captures,
2977                next_capture: None,
2978                stack: Default::default(),
2979                highlight_maps,
2980            })
2981        }
2982
2983        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
2984        let chunks = text.chunks_in_range(range.clone());
2985
2986        BufferChunks {
2987            range,
2988            chunks,
2989            diagnostic_endpoints,
2990            error_depth: 0,
2991            warning_depth: 0,
2992            information_depth: 0,
2993            hint_depth: 0,
2994            unnecessary_depth: 0,
2995            highlights,
2996        }
2997    }
2998
2999    pub fn seek(&mut self, offset: usize) {
3000        self.range.start = offset;
3001        self.chunks.seek(self.range.start);
3002        if let Some(highlights) = self.highlights.as_mut() {
3003            highlights
3004                .stack
3005                .retain(|(end_offset, _)| *end_offset > offset);
3006            if let Some(capture) = &highlights.next_capture {
3007                if offset >= capture.node.start_byte() {
3008                    let next_capture_end = capture.node.end_byte();
3009                    if offset < next_capture_end {
3010                        highlights.stack.push((
3011                            next_capture_end,
3012                            highlights.highlight_maps[capture.grammar_index].get(capture.index),
3013                        ));
3014                    }
3015                    highlights.next_capture.take();
3016                }
3017            }
3018            highlights.captures.set_byte_range(self.range.clone());
3019        }
3020    }
3021
3022    pub fn offset(&self) -> usize {
3023        self.range.start
3024    }
3025
3026    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
3027        let depth = match endpoint.severity {
3028            DiagnosticSeverity::ERROR => &mut self.error_depth,
3029            DiagnosticSeverity::WARNING => &mut self.warning_depth,
3030            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
3031            DiagnosticSeverity::HINT => &mut self.hint_depth,
3032            _ => return,
3033        };
3034        if endpoint.is_start {
3035            *depth += 1;
3036        } else {
3037            *depth -= 1;
3038        }
3039
3040        if endpoint.is_unnecessary {
3041            if endpoint.is_start {
3042                self.unnecessary_depth += 1;
3043            } else {
3044                self.unnecessary_depth -= 1;
3045            }
3046        }
3047    }
3048
3049    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
3050        if self.error_depth > 0 {
3051            Some(DiagnosticSeverity::ERROR)
3052        } else if self.warning_depth > 0 {
3053            Some(DiagnosticSeverity::WARNING)
3054        } else if self.information_depth > 0 {
3055            Some(DiagnosticSeverity::INFORMATION)
3056        } else if self.hint_depth > 0 {
3057            Some(DiagnosticSeverity::HINT)
3058        } else {
3059            None
3060        }
3061    }
3062
3063    fn current_code_is_unnecessary(&self) -> bool {
3064        self.unnecessary_depth > 0
3065    }
3066}
3067
3068impl<'a> Iterator for BufferChunks<'a> {
3069    type Item = Chunk<'a>;
3070
3071    fn next(&mut self) -> Option<Self::Item> {
3072        let mut next_capture_start = usize::MAX;
3073        let mut next_diagnostic_endpoint = usize::MAX;
3074
3075        if let Some(highlights) = self.highlights.as_mut() {
3076            while let Some((parent_capture_end, _)) = highlights.stack.last() {
3077                if *parent_capture_end <= self.range.start {
3078                    highlights.stack.pop();
3079                } else {
3080                    break;
3081                }
3082            }
3083
3084            if highlights.next_capture.is_none() {
3085                highlights.next_capture = highlights.captures.next();
3086            }
3087
3088            while let Some(capture) = highlights.next_capture.as_ref() {
3089                if self.range.start < capture.node.start_byte() {
3090                    next_capture_start = capture.node.start_byte();
3091                    break;
3092                } else {
3093                    let highlight_id =
3094                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
3095                    highlights
3096                        .stack
3097                        .push((capture.node.end_byte(), highlight_id));
3098                    highlights.next_capture = highlights.captures.next();
3099                }
3100            }
3101        }
3102
3103        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
3104            if endpoint.offset <= self.range.start {
3105                self.update_diagnostic_depths(endpoint);
3106                self.diagnostic_endpoints.next();
3107            } else {
3108                next_diagnostic_endpoint = endpoint.offset;
3109                break;
3110            }
3111        }
3112
3113        if let Some(chunk) = self.chunks.peek() {
3114            let chunk_start = self.range.start;
3115            let mut chunk_end = (self.chunks.offset() + chunk.len())
3116                .min(next_capture_start)
3117                .min(next_diagnostic_endpoint);
3118            let mut highlight_id = None;
3119            if let Some(highlights) = self.highlights.as_ref() {
3120                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
3121                    chunk_end = chunk_end.min(*parent_capture_end);
3122                    highlight_id = Some(*parent_highlight_id);
3123                }
3124            }
3125
3126            let slice =
3127                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
3128            self.range.start = chunk_end;
3129            if self.range.start == self.chunks.offset() + chunk.len() {
3130                self.chunks.next().unwrap();
3131            }
3132
3133            Some(Chunk {
3134                text: slice,
3135                syntax_highlight_id: highlight_id,
3136                diagnostic_severity: self.current_diagnostic_severity(),
3137                is_unnecessary: self.current_code_is_unnecessary(),
3138                ..Default::default()
3139            })
3140        } else {
3141            None
3142        }
3143    }
3144}
3145
3146impl operation_queue::Operation for Operation {
3147    fn lamport_timestamp(&self) -> clock::Lamport {
3148        match self {
3149            Operation::Buffer(_) => {
3150                unreachable!("buffer operations should never be deferred at this layer")
3151            }
3152            Operation::UpdateDiagnostics {
3153                lamport_timestamp, ..
3154            }
3155            | Operation::UpdateSelections {
3156                lamport_timestamp, ..
3157            }
3158            | Operation::UpdateCompletionTriggers {
3159                lamport_timestamp, ..
3160            } => *lamport_timestamp,
3161        }
3162    }
3163}
3164
3165impl Default for Diagnostic {
3166    fn default() -> Self {
3167        Self {
3168            source: Default::default(),
3169            code: None,
3170            severity: DiagnosticSeverity::ERROR,
3171            message: Default::default(),
3172            group_id: 0,
3173            is_primary: false,
3174            is_valid: true,
3175            is_disk_based: false,
3176            is_unnecessary: false,
3177        }
3178    }
3179}
3180
3181impl IndentSize {
3182    pub fn spaces(len: u32) -> Self {
3183        Self {
3184            len,
3185            kind: IndentKind::Space,
3186        }
3187    }
3188
3189    pub fn tab() -> Self {
3190        Self {
3191            len: 1,
3192            kind: IndentKind::Tab,
3193        }
3194    }
3195
3196    pub fn chars(&self) -> impl Iterator<Item = char> {
3197        iter::repeat(self.char()).take(self.len as usize)
3198    }
3199
3200    pub fn char(&self) -> char {
3201        match self.kind {
3202            IndentKind::Space => ' ',
3203            IndentKind::Tab => '\t',
3204        }
3205    }
3206
3207    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
3208        match direction {
3209            Ordering::Less => {
3210                if self.kind == size.kind && self.len >= size.len {
3211                    self.len -= size.len;
3212                }
3213            }
3214            Ordering::Equal => {}
3215            Ordering::Greater => {
3216                if self.len == 0 {
3217                    self = size;
3218                } else if self.kind == size.kind {
3219                    self.len += size.len;
3220                }
3221            }
3222        }
3223        self
3224    }
3225}
3226
3227impl Completion {
3228    pub fn sort_key(&self) -> (usize, &str) {
3229        let kind_key = match self.lsp_completion.kind {
3230            Some(lsp::CompletionItemKind::VARIABLE) => 0,
3231            _ => 1,
3232        };
3233        (kind_key, &self.label.text[self.label.filter_range.clone()])
3234    }
3235
3236    pub fn is_snippet(&self) -> bool {
3237        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
3238    }
3239}
3240
3241pub fn contiguous_ranges(
3242    values: impl Iterator<Item = u32>,
3243    max_len: usize,
3244) -> impl Iterator<Item = Range<u32>> {
3245    let mut values = values;
3246    let mut current_range: Option<Range<u32>> = None;
3247    std::iter::from_fn(move || loop {
3248        if let Some(value) = values.next() {
3249            if let Some(range) = &mut current_range {
3250                if value == range.end && range.len() < max_len {
3251                    range.end += 1;
3252                    continue;
3253                }
3254            }
3255
3256            let prev_range = current_range.clone();
3257            current_range = Some(value..(value + 1));
3258            if prev_range.is_some() {
3259                return prev_range;
3260            }
3261        } else {
3262            return current_range.take();
3263        }
3264    })
3265}
3266
3267pub fn char_kind(scope: &Option<LanguageScope>, c: char) -> CharKind {
3268    if c.is_whitespace() {
3269        return CharKind::Whitespace;
3270    } else if c.is_alphanumeric() || c == '_' {
3271        return CharKind::Word;
3272    }
3273
3274    if let Some(scope) = scope {
3275        if let Some(characters) = scope.word_characters() {
3276            if characters.contains(&c) {
3277                return CharKind::Word;
3278            }
3279        }
3280    }
3281
3282    CharKind::Punctuation
3283}
3284
3285/// Find all of the ranges of whitespace that occur at the ends of lines
3286/// in the given rope.
3287///
3288/// This could also be done with a regex search, but this implementation
3289/// avoids copying text.
3290pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
3291    let mut ranges = Vec::new();
3292
3293    let mut offset = 0;
3294    let mut prev_chunk_trailing_whitespace_range = 0..0;
3295    for chunk in rope.chunks() {
3296        let mut prev_line_trailing_whitespace_range = 0..0;
3297        for (i, line) in chunk.split('\n').enumerate() {
3298            let line_end_offset = offset + line.len();
3299            let trimmed_line_len = line.trim_end_matches(|c| matches!(c, ' ' | '\t')).len();
3300            let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
3301
3302            if i == 0 && trimmed_line_len == 0 {
3303                trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
3304            }
3305            if !prev_line_trailing_whitespace_range.is_empty() {
3306                ranges.push(prev_line_trailing_whitespace_range);
3307            }
3308
3309            offset = line_end_offset + 1;
3310            prev_line_trailing_whitespace_range = trailing_whitespace_range;
3311        }
3312
3313        offset -= 1;
3314        prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
3315    }
3316
3317    if !prev_chunk_trailing_whitespace_range.is_empty() {
3318        ranges.push(prev_chunk_trailing_whitespace_range);
3319    }
3320
3321    ranges
3322}