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