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