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