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