buffer.rs

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