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