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