buffer.rs

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