buffer.rs

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