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