buffer.rs

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