buffer.rs

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