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