buffer.rs

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