buffer.rs

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