buffer.rs

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