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