buffer.rs

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