buffer.rs

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