buffer.rs

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