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