buffer.rs

   1use crate::diagnostic_set::{DiagnosticEntry, DiagnosticGroup};
   2pub use crate::{
   3    diagnostic_set::DiagnosticSet,
   4    highlight_map::{HighlightId, HighlightMap},
   5    proto, BracketPair, Grammar, Language, LanguageConfig, LanguageRegistry, LanguageServerConfig,
   6    PLAIN_TEXT,
   7};
   8use anyhow::{anyhow, Result};
   9use clock::ReplicaId;
  10use futures::FutureExt as _;
  11use gpui::{fonts::HighlightStyle, AppContext, Entity, ModelContext, MutableAppContext, Task};
  12use lazy_static::lazy_static;
  13use lsp::LanguageServer;
  14use parking_lot::Mutex;
  15use postage::{prelude::Stream, sink::Sink, watch};
  16use similar::{ChangeTag, TextDiff};
  17use smol::future::yield_now;
  18use std::{
  19    any::Any,
  20    cell::RefCell,
  21    cmp::{self, Ordering},
  22    collections::{BTreeMap, HashMap},
  23    ffi::OsString,
  24    future::Future,
  25    iter::{Iterator, Peekable},
  26    ops::{Deref, DerefMut, Range, Sub},
  27    path::{Path, PathBuf},
  28    str,
  29    sync::Arc,
  30    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
  31    vec,
  32};
  33use sum_tree::TreeMap;
  34use text::{operation_queue::OperationQueue, rope::TextDimension};
  35pub use text::{Buffer as TextBuffer, Operation as _, *};
  36use theme::SyntaxTheme;
  37use tree_sitter::{InputEdit, Parser, QueryCursor, Tree};
  38use util::{post_inc, TryFutureExt as _};
  39
  40#[cfg(any(test, feature = "test-support"))]
  41pub use tree_sitter_rust;
  42
  43pub use lsp::DiagnosticSeverity;
  44
  45thread_local! {
  46    static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
  47}
  48
  49lazy_static! {
  50    static ref QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Default::default();
  51}
  52
  53// TODO - Make this configurable
  54const INDENT_SIZE: u32 = 4;
  55
  56pub struct Buffer {
  57    text: TextBuffer,
  58    file: Option<Box<dyn File>>,
  59    saved_version: clock::Global,
  60    saved_mtime: SystemTime,
  61    language: Option<Arc<Language>>,
  62    autoindent_requests: Vec<Arc<AutoindentRequest>>,
  63    pending_autoindent: Option<Task<()>>,
  64    sync_parse_timeout: Duration,
  65    syntax_tree: Mutex<Option<SyntaxTree>>,
  66    parsing_in_background: bool,
  67    parse_count: usize,
  68    remote_selections: TreeMap<ReplicaId, Arc<[Selection<Anchor>]>>,
  69    selections_update_count: usize,
  70    diagnostic_sets: Vec<DiagnosticSet>,
  71    diagnostics_update_count: usize,
  72    language_server: Option<LanguageServerState>,
  73    deferred_ops: OperationQueue<Operation>,
  74    #[cfg(test)]
  75    pub(crate) operations: Vec<Operation>,
  76}
  77
  78pub struct BufferSnapshot {
  79    text: text::BufferSnapshot,
  80    tree: Option<Tree>,
  81    diagnostic_sets: Vec<DiagnosticSet>,
  82    diagnostics_update_count: usize,
  83    remote_selections: TreeMap<ReplicaId, Arc<[Selection<Anchor>]>>,
  84    selections_update_count: usize,
  85    is_parsing: bool,
  86    language: Option<Arc<Language>>,
  87    parse_count: usize,
  88}
  89
  90#[derive(Clone, Debug, PartialEq, Eq)]
  91pub struct GroupId {
  92    source: Arc<str>,
  93    id: usize,
  94}
  95
  96#[derive(Clone, Debug, PartialEq, Eq)]
  97pub struct Diagnostic {
  98    pub code: Option<String>,
  99    pub severity: DiagnosticSeverity,
 100    pub message: String,
 101    pub group_id: usize,
 102    pub is_valid: bool,
 103    pub is_primary: bool,
 104    pub is_disk_based: bool,
 105}
 106
 107struct LanguageServerState {
 108    server: Arc<LanguageServer>,
 109    latest_snapshot: watch::Sender<Option<LanguageServerSnapshot>>,
 110    pending_snapshots: BTreeMap<usize, LanguageServerSnapshot>,
 111    next_version: usize,
 112    _maintain_server: Task<Option<()>>,
 113}
 114
 115#[derive(Clone)]
 116struct LanguageServerSnapshot {
 117    buffer_snapshot: text::BufferSnapshot,
 118    version: usize,
 119    path: Arc<Path>,
 120}
 121
 122#[derive(Clone, Debug)]
 123pub enum Operation {
 124    Buffer(text::Operation),
 125    UpdateDiagnostics {
 126        provider_name: String,
 127        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
 128        lamport_timestamp: clock::Lamport,
 129    },
 130    UpdateSelections {
 131        replica_id: ReplicaId,
 132        selections: Arc<[Selection<Anchor>]>,
 133        lamport_timestamp: clock::Lamport,
 134    },
 135    RemoveSelections {
 136        replica_id: ReplicaId,
 137        lamport_timestamp: clock::Lamport,
 138    },
 139}
 140
 141#[derive(Clone, Debug, Eq, PartialEq)]
 142pub enum Event {
 143    Edited,
 144    Dirtied,
 145    Saved,
 146    FileHandleChanged,
 147    Reloaded,
 148    Reparsed,
 149    DiagnosticsUpdated,
 150    Closed,
 151}
 152
 153pub trait File {
 154    fn mtime(&self) -> SystemTime;
 155
 156    /// Returns the path of this file relative to the worktree's root directory.
 157    fn path(&self) -> &Arc<Path>;
 158
 159    /// Returns the absolute path of this file.
 160    fn abs_path(&self) -> Option<PathBuf>;
 161
 162    /// Returns the path of this file relative to the worktree's parent directory (this means it
 163    /// includes the name of the worktree's root folder).
 164    fn full_path(&self) -> PathBuf;
 165
 166    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 167    /// of its worktree, then this method will return the name of the worktree itself.
 168    fn file_name(&self) -> Option<OsString>;
 169
 170    fn is_deleted(&self) -> bool;
 171
 172    fn save(
 173        &self,
 174        buffer_id: u64,
 175        text: Rope,
 176        version: clock::Global,
 177        cx: &mut MutableAppContext,
 178    ) -> Task<Result<(clock::Global, SystemTime)>>;
 179
 180    fn load_local(&self, cx: &AppContext) -> Option<Task<Result<String>>>;
 181
 182    fn buffer_updated(&self, buffer_id: u64, operation: Operation, cx: &mut MutableAppContext);
 183
 184    fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext);
 185
 186    fn as_any(&self) -> &dyn Any;
 187}
 188
 189struct QueryCursorHandle(Option<QueryCursor>);
 190
 191#[derive(Clone)]
 192struct SyntaxTree {
 193    tree: Tree,
 194    version: clock::Global,
 195}
 196
 197#[derive(Clone)]
 198struct AutoindentRequest {
 199    before_edit: BufferSnapshot,
 200    edited: Vec<Anchor>,
 201    inserted: Option<Vec<Range<Anchor>>>,
 202}
 203
 204#[derive(Debug)]
 205struct IndentSuggestion {
 206    basis_row: u32,
 207    indent: bool,
 208}
 209
 210struct TextProvider<'a>(&'a Rope);
 211
 212struct BufferChunkHighlights<'a> {
 213    captures: tree_sitter::QueryCaptures<'a, 'a, TextProvider<'a>>,
 214    next_capture: Option<(tree_sitter::QueryMatch<'a, 'a>, usize)>,
 215    stack: Vec<(usize, HighlightId)>,
 216    highlight_map: HighlightMap,
 217    theme: &'a SyntaxTheme,
 218    _query_cursor: QueryCursorHandle,
 219}
 220
 221pub struct BufferChunks<'a> {
 222    range: Range<usize>,
 223    chunks: rope::Chunks<'a>,
 224    diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
 225    error_depth: usize,
 226    warning_depth: usize,
 227    information_depth: usize,
 228    hint_depth: usize,
 229    highlights: Option<BufferChunkHighlights<'a>>,
 230}
 231
 232#[derive(Clone, Copy, Debug, Default)]
 233pub struct Chunk<'a> {
 234    pub text: &'a str,
 235    pub highlight_style: Option<HighlightStyle>,
 236    pub diagnostic: Option<DiagnosticSeverity>,
 237}
 238
 239pub(crate) struct Diff {
 240    base_version: clock::Global,
 241    new_text: Arc<str>,
 242    changes: Vec<(ChangeTag, usize)>,
 243}
 244
 245#[derive(Clone, Copy)]
 246struct DiagnosticEndpoint {
 247    offset: usize,
 248    is_start: bool,
 249    severity: DiagnosticSeverity,
 250}
 251
 252impl Buffer {
 253    pub fn new<T: Into<Arc<str>>>(
 254        replica_id: ReplicaId,
 255        base_text: T,
 256        cx: &mut ModelContext<Self>,
 257    ) -> Self {
 258        Self::build(
 259            TextBuffer::new(
 260                replica_id,
 261                cx.model_id() as u64,
 262                History::new(base_text.into()),
 263            ),
 264            None,
 265        )
 266    }
 267
 268    pub fn from_file<T: Into<Arc<str>>>(
 269        replica_id: ReplicaId,
 270        base_text: T,
 271        file: Box<dyn File>,
 272        cx: &mut ModelContext<Self>,
 273    ) -> Self {
 274        Self::build(
 275            TextBuffer::new(
 276                replica_id,
 277                cx.model_id() as u64,
 278                History::new(base_text.into()),
 279            ),
 280            Some(file),
 281        )
 282    }
 283
 284    pub fn from_proto(
 285        replica_id: ReplicaId,
 286        message: proto::Buffer,
 287        file: Option<Box<dyn File>>,
 288        cx: &mut ModelContext<Self>,
 289    ) -> Result<Self> {
 290        let fragments_len = message.fragments.len();
 291        let buffer = TextBuffer::from_parts(
 292            replica_id,
 293            message.id,
 294            &message.visible_text,
 295            &message.deleted_text,
 296            message
 297                .undo_map
 298                .into_iter()
 299                .map(proto::deserialize_undo_map_entry),
 300            message
 301                .fragments
 302                .into_iter()
 303                .enumerate()
 304                .map(|(i, fragment)| {
 305                    proto::deserialize_buffer_fragment(fragment, i, fragments_len)
 306                }),
 307            message.lamport_timestamp,
 308            From::from(message.version),
 309        );
 310        let mut this = Self::build(buffer, file);
 311        for selection_set in message.selections {
 312            this.remote_selections.insert(
 313                selection_set.replica_id as ReplicaId,
 314                proto::deserialize_selections(selection_set.selections),
 315            );
 316        }
 317        let snapshot = this.snapshot();
 318        for diagnostic_set in message.diagnostic_sets {
 319            let (provider_name, entries) = proto::deserialize_diagnostic_set(diagnostic_set);
 320            this.apply_diagnostic_update(
 321                DiagnosticSet::from_sorted_entries(
 322                    provider_name,
 323                    entries.into_iter().cloned(),
 324                    &snapshot,
 325                ),
 326                cx,
 327            );
 328        }
 329
 330        Ok(this)
 331    }
 332
 333    pub fn to_proto(&self) -> proto::Buffer {
 334        proto::Buffer {
 335            id: self.remote_id(),
 336            visible_text: self.text.text(),
 337            deleted_text: self.text.deleted_text(),
 338            undo_map: self
 339                .text
 340                .undo_history()
 341                .map(proto::serialize_undo_map_entry)
 342                .collect(),
 343            version: From::from(&self.version),
 344            lamport_timestamp: self.lamport_clock.value,
 345            fragments: self
 346                .text
 347                .fragments()
 348                .map(proto::serialize_buffer_fragment)
 349                .collect(),
 350            selections: self
 351                .remote_selections
 352                .iter()
 353                .map(|(replica_id, selections)| proto::SelectionSet {
 354                    replica_id: *replica_id as u32,
 355                    selections: proto::serialize_selections(selections),
 356                })
 357                .collect(),
 358            diagnostic_sets: self
 359                .diagnostic_sets
 360                .iter()
 361                .map(|set| {
 362                    proto::serialize_diagnostic_set(set.provider_name().to_string(), set.iter())
 363                })
 364                .collect(),
 365        }
 366    }
 367
 368    pub fn with_language(
 369        mut self,
 370        language: Option<Arc<Language>>,
 371        language_server: Option<Arc<LanguageServer>>,
 372        cx: &mut ModelContext<Self>,
 373    ) -> Self {
 374        self.set_language(language, language_server, cx);
 375        self
 376    }
 377
 378    fn build(buffer: TextBuffer, file: Option<Box<dyn File>>) -> Self {
 379        let saved_mtime;
 380        if let Some(file) = file.as_ref() {
 381            saved_mtime = file.mtime();
 382        } else {
 383            saved_mtime = UNIX_EPOCH;
 384        }
 385
 386        Self {
 387            saved_mtime,
 388            saved_version: buffer.version(),
 389            text: buffer,
 390            file,
 391            syntax_tree: Mutex::new(None),
 392            parsing_in_background: false,
 393            parse_count: 0,
 394            sync_parse_timeout: Duration::from_millis(1),
 395            autoindent_requests: Default::default(),
 396            pending_autoindent: Default::default(),
 397            language: None,
 398            remote_selections: Default::default(),
 399            selections_update_count: 0,
 400            diagnostic_sets: Default::default(),
 401            diagnostics_update_count: 0,
 402            language_server: None,
 403            deferred_ops: OperationQueue::new(),
 404            #[cfg(test)]
 405            operations: Default::default(),
 406        }
 407    }
 408
 409    pub fn snapshot(&self) -> BufferSnapshot {
 410        BufferSnapshot {
 411            text: self.text.snapshot(),
 412            tree: self.syntax_tree(),
 413            remote_selections: self.remote_selections.clone(),
 414            diagnostic_sets: self.diagnostic_sets.clone(),
 415            diagnostics_update_count: self.diagnostics_update_count,
 416            is_parsing: self.parsing_in_background,
 417            language: self.language.clone(),
 418            parse_count: self.parse_count,
 419            selections_update_count: self.selections_update_count,
 420        }
 421    }
 422
 423    pub fn file(&self) -> Option<&dyn File> {
 424        self.file.as_deref()
 425    }
 426
 427    pub fn save(
 428        &mut self,
 429        cx: &mut ModelContext<Self>,
 430    ) -> Result<Task<Result<(clock::Global, SystemTime)>>> {
 431        let file = self
 432            .file
 433            .as_ref()
 434            .ok_or_else(|| anyhow!("buffer has no file"))?;
 435        let text = self.as_rope().clone();
 436        let version = self.version();
 437        let save = file.save(self.remote_id(), text, version, cx.as_mut());
 438        Ok(cx.spawn(|this, mut cx| async move {
 439            let (version, mtime) = save.await?;
 440            this.update(&mut cx, |this, cx| {
 441                this.did_save(version.clone(), mtime, None, cx);
 442            });
 443            Ok((version, mtime))
 444        }))
 445    }
 446
 447    pub fn set_language(
 448        &mut self,
 449        language: Option<Arc<Language>>,
 450        language_server: Option<Arc<lsp::LanguageServer>>,
 451        cx: &mut ModelContext<Self>,
 452    ) {
 453        self.language = language;
 454        self.language_server = if let Some(server) = language_server {
 455            let (latest_snapshot_tx, mut latest_snapshot_rx) = watch::channel();
 456            Some(LanguageServerState {
 457                latest_snapshot: latest_snapshot_tx,
 458                pending_snapshots: Default::default(),
 459                next_version: 0,
 460                server: server.clone(),
 461                _maintain_server: cx.background().spawn(
 462                    async move {
 463                        let mut prev_snapshot: Option<LanguageServerSnapshot> = None;
 464                        while let Some(snapshot) = latest_snapshot_rx.recv().await {
 465                            if let Some(snapshot) = snapshot {
 466                                let uri = lsp::Url::from_file_path(&snapshot.path).unwrap();
 467                                if let Some(prev_snapshot) = prev_snapshot {
 468                                    let changes = lsp::DidChangeTextDocumentParams {
 469                                        text_document: lsp::VersionedTextDocumentIdentifier::new(
 470                                            uri,
 471                                            snapshot.version as i32,
 472                                        ),
 473                                        content_changes: snapshot
 474                                            .buffer_snapshot
 475                                            .edits_since::<(PointUtf16, usize)>(
 476                                                prev_snapshot.buffer_snapshot.version(),
 477                                            )
 478                                            .map(|edit| {
 479                                                let edit_start = edit.new.start.0;
 480                                                let edit_end = edit_start
 481                                                    + (edit.old.end.0 - edit.old.start.0);
 482                                                let new_text = snapshot
 483                                                    .buffer_snapshot
 484                                                    .text_for_range(
 485                                                        edit.new.start.1..edit.new.end.1,
 486                                                    )
 487                                                    .collect();
 488                                                lsp::TextDocumentContentChangeEvent {
 489                                                    range: Some(lsp::Range::new(
 490                                                        lsp::Position::new(
 491                                                            edit_start.row,
 492                                                            edit_start.column,
 493                                                        ),
 494                                                        lsp::Position::new(
 495                                                            edit_end.row,
 496                                                            edit_end.column,
 497                                                        ),
 498                                                    )),
 499                                                    range_length: None,
 500                                                    text: new_text,
 501                                                }
 502                                            })
 503                                            .collect(),
 504                                    };
 505                                    server
 506                                        .notify::<lsp::notification::DidChangeTextDocument>(changes)
 507                                        .await?;
 508                                } else {
 509                                    server
 510                                        .notify::<lsp::notification::DidOpenTextDocument>(
 511                                            lsp::DidOpenTextDocumentParams {
 512                                                text_document: lsp::TextDocumentItem::new(
 513                                                    uri,
 514                                                    Default::default(),
 515                                                    snapshot.version as i32,
 516                                                    snapshot.buffer_snapshot.text().to_string(),
 517                                                ),
 518                                            },
 519                                        )
 520                                        .await?;
 521                                }
 522
 523                                prev_snapshot = Some(snapshot);
 524                            }
 525                        }
 526                        Ok(())
 527                    }
 528                    .log_err(),
 529                ),
 530            })
 531        } else {
 532            None
 533        };
 534
 535        self.reparse(cx);
 536        self.update_language_server();
 537    }
 538
 539    pub fn did_save(
 540        &mut self,
 541        version: clock::Global,
 542        mtime: SystemTime,
 543        new_file: Option<Box<dyn File>>,
 544        cx: &mut ModelContext<Self>,
 545    ) {
 546        self.saved_mtime = mtime;
 547        self.saved_version = version;
 548        if let Some(new_file) = new_file {
 549            self.file = Some(new_file);
 550        }
 551        if let Some(state) = &self.language_server {
 552            cx.background()
 553                .spawn(
 554                    state
 555                        .server
 556                        .notify::<lsp::notification::DidSaveTextDocument>(
 557                            lsp::DidSaveTextDocumentParams {
 558                                text_document: lsp::TextDocumentIdentifier {
 559                                    uri: lsp::Url::from_file_path(
 560                                        self.file.as_ref().unwrap().abs_path().unwrap(),
 561                                    )
 562                                    .unwrap(),
 563                                },
 564                                text: None,
 565                            },
 566                        ),
 567                )
 568                .detach()
 569        }
 570        cx.emit(Event::Saved);
 571    }
 572
 573    pub fn file_updated(
 574        &mut self,
 575        new_file: Box<dyn File>,
 576        cx: &mut ModelContext<Self>,
 577    ) -> Option<Task<()>> {
 578        let old_file = self.file.as_ref()?;
 579        let mut file_changed = false;
 580        let mut task = None;
 581
 582        if new_file.path() != old_file.path() {
 583            file_changed = true;
 584        }
 585
 586        if new_file.is_deleted() {
 587            if !old_file.is_deleted() {
 588                file_changed = true;
 589                if !self.is_dirty() {
 590                    cx.emit(Event::Dirtied);
 591                }
 592            }
 593        } else {
 594            let new_mtime = new_file.mtime();
 595            if new_mtime != old_file.mtime() {
 596                file_changed = true;
 597
 598                if !self.is_dirty() {
 599                    task = Some(cx.spawn(|this, mut cx| {
 600                        async move {
 601                            let new_text = this.read_with(&cx, |this, cx| {
 602                                this.file.as_ref().and_then(|file| file.load_local(cx))
 603                            });
 604                            if let Some(new_text) = new_text {
 605                                let new_text = new_text.await?;
 606                                let diff = this
 607                                    .read_with(&cx, |this, cx| this.diff(new_text.into(), cx))
 608                                    .await;
 609                                this.update(&mut cx, |this, cx| {
 610                                    if this.apply_diff(diff, cx) {
 611                                        this.saved_version = this.version();
 612                                        this.saved_mtime = new_mtime;
 613                                        cx.emit(Event::Reloaded);
 614                                    }
 615                                });
 616                            }
 617                            Ok(())
 618                        }
 619                        .log_err()
 620                        .map(drop)
 621                    }));
 622                }
 623            }
 624        }
 625
 626        if file_changed {
 627            cx.emit(Event::FileHandleChanged);
 628        }
 629        self.file = Some(new_file);
 630        task
 631    }
 632
 633    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 634        cx.emit(Event::Closed);
 635    }
 636
 637    pub fn language(&self) -> Option<&Arc<Language>> {
 638        self.language.as_ref()
 639    }
 640
 641    pub fn parse_count(&self) -> usize {
 642        self.parse_count
 643    }
 644
 645    pub fn selections_update_count(&self) -> usize {
 646        self.selections_update_count
 647    }
 648
 649    pub fn diagnostics_update_count(&self) -> usize {
 650        self.diagnostics_update_count
 651    }
 652
 653    pub(crate) fn syntax_tree(&self) -> Option<Tree> {
 654        if let Some(syntax_tree) = self.syntax_tree.lock().as_mut() {
 655            self.interpolate_tree(syntax_tree);
 656            Some(syntax_tree.tree.clone())
 657        } else {
 658            None
 659        }
 660    }
 661
 662    #[cfg(any(test, feature = "test-support"))]
 663    pub fn is_parsing(&self) -> bool {
 664        self.parsing_in_background
 665    }
 666
 667    #[cfg(test)]
 668    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
 669        self.sync_parse_timeout = timeout;
 670    }
 671
 672    fn reparse(&mut self, cx: &mut ModelContext<Self>) -> bool {
 673        if self.parsing_in_background {
 674            return false;
 675        }
 676
 677        if let Some(grammar) = self.grammar().cloned() {
 678            let old_tree = self.syntax_tree();
 679            let text = self.as_rope().clone();
 680            let parsed_version = self.version();
 681            let parse_task = cx.background().spawn({
 682                let grammar = grammar.clone();
 683                async move { Self::parse_text(&text, old_tree, &grammar) }
 684            });
 685
 686            match cx
 687                .background()
 688                .block_with_timeout(self.sync_parse_timeout, parse_task)
 689            {
 690                Ok(new_tree) => {
 691                    self.did_finish_parsing(new_tree, parsed_version, cx);
 692                    return true;
 693                }
 694                Err(parse_task) => {
 695                    self.parsing_in_background = true;
 696                    cx.spawn(move |this, mut cx| async move {
 697                        let new_tree = parse_task.await;
 698                        this.update(&mut cx, move |this, cx| {
 699                            let grammar_changed = this
 700                                .grammar()
 701                                .map_or(true, |curr_grammar| !Arc::ptr_eq(&grammar, curr_grammar));
 702                            let parse_again = this.version.gt(&parsed_version) || grammar_changed;
 703                            this.parsing_in_background = false;
 704                            this.did_finish_parsing(new_tree, parsed_version, cx);
 705
 706                            if parse_again && this.reparse(cx) {
 707                                return;
 708                            }
 709                        });
 710                    })
 711                    .detach();
 712                }
 713            }
 714        }
 715        false
 716    }
 717
 718    fn parse_text(text: &Rope, old_tree: Option<Tree>, grammar: &Grammar) -> Tree {
 719        PARSER.with(|parser| {
 720            let mut parser = parser.borrow_mut();
 721            parser
 722                .set_language(grammar.ts_language)
 723                .expect("incompatible grammar");
 724            let mut chunks = text.chunks_in_range(0..text.len());
 725            let tree = parser
 726                .parse_with(
 727                    &mut move |offset, _| {
 728                        chunks.seek(offset);
 729                        chunks.next().unwrap_or("").as_bytes()
 730                    },
 731                    old_tree.as_ref(),
 732                )
 733                .unwrap();
 734            tree
 735        })
 736    }
 737
 738    fn interpolate_tree(&self, tree: &mut SyntaxTree) {
 739        for edit in self.edits_since::<(usize, Point)>(&tree.version) {
 740            let (bytes, lines) = edit.flatten();
 741            tree.tree.edit(&InputEdit {
 742                start_byte: bytes.new.start,
 743                old_end_byte: bytes.new.start + bytes.old.len(),
 744                new_end_byte: bytes.new.end,
 745                start_position: lines.new.start.to_ts_point(),
 746                old_end_position: (lines.new.start + (lines.old.end - lines.old.start))
 747                    .to_ts_point(),
 748                new_end_position: lines.new.end.to_ts_point(),
 749            });
 750        }
 751        tree.version = self.version();
 752    }
 753
 754    fn did_finish_parsing(
 755        &mut self,
 756        tree: Tree,
 757        version: clock::Global,
 758        cx: &mut ModelContext<Self>,
 759    ) {
 760        self.parse_count += 1;
 761        *self.syntax_tree.lock() = Some(SyntaxTree { tree, version });
 762        self.request_autoindent(cx);
 763        cx.emit(Event::Reparsed);
 764        cx.notify();
 765    }
 766
 767    pub fn update_diagnostics<T>(
 768        &mut self,
 769        provider_name: Arc<str>,
 770        version: Option<i32>,
 771        mut diagnostics: Vec<DiagnosticEntry<T>>,
 772        cx: &mut ModelContext<Self>,
 773    ) -> Result<Operation>
 774    where
 775        T: Copy + Ord + TextDimension + Sub<Output = T> + Clip + ToPoint,
 776    {
 777        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
 778            Ordering::Equal
 779                .then_with(|| b.is_primary.cmp(&a.is_primary))
 780                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
 781                .then_with(|| a.severity.cmp(&b.severity))
 782                .then_with(|| a.message.cmp(&b.message))
 783        }
 784
 785        let version = version.map(|version| version as usize);
 786        let content = if let Some(version) = version {
 787            let language_server = self.language_server.as_mut().unwrap();
 788            language_server
 789                .pending_snapshots
 790                .retain(|&v, _| v >= version);
 791            let snapshot = language_server
 792                .pending_snapshots
 793                .get(&version)
 794                .ok_or_else(|| anyhow!("missing snapshot"))?;
 795            &snapshot.buffer_snapshot
 796        } else {
 797            self.deref()
 798        };
 799
 800        diagnostics.sort_unstable_by(|a, b| {
 801            Ordering::Equal
 802                .then_with(|| a.range.start.cmp(&b.range.start))
 803                .then_with(|| b.range.end.cmp(&a.range.end))
 804                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
 805        });
 806
 807        let mut sanitized_diagnostics = Vec::new();
 808        let mut edits_since_save = content.edits_since::<T>(&self.saved_version).peekable();
 809        let mut last_edit_old_end = T::default();
 810        let mut last_edit_new_end = T::default();
 811        'outer: for entry in diagnostics {
 812            let mut start = entry.range.start;
 813            let mut end = entry.range.end;
 814
 815            // Some diagnostics are based on files on disk instead of buffers'
 816            // current contents. Adjust these diagnostics' ranges to reflect
 817            // any unsaved edits.
 818            if entry.diagnostic.is_disk_based {
 819                while let Some(edit) = edits_since_save.peek() {
 820                    if edit.old.end <= start {
 821                        last_edit_old_end = edit.old.end;
 822                        last_edit_new_end = edit.new.end;
 823                        edits_since_save.next();
 824                    } else if edit.old.start <= end && edit.old.end >= start {
 825                        continue 'outer;
 826                    } else {
 827                        break;
 828                    }
 829                }
 830
 831                let start_overshoot = start - last_edit_old_end;
 832                start = last_edit_new_end;
 833                start.add_assign(&start_overshoot);
 834
 835                let end_overshoot = end - last_edit_old_end;
 836                end = last_edit_new_end;
 837                end.add_assign(&end_overshoot);
 838            }
 839
 840            let range = start.clip(Bias::Left, content)..end.clip(Bias::Right, content);
 841            let mut range = range.start.to_point(content)..range.end.to_point(content);
 842            // Expand empty ranges by one character
 843            if range.start == range.end {
 844                range.end.column += 1;
 845                range.end = content.clip_point(range.end, Bias::Right);
 846                if range.start == range.end && range.end.column > 0 {
 847                    range.start.column -= 1;
 848                    range.start = content.clip_point(range.start, Bias::Left);
 849                }
 850            }
 851
 852            sanitized_diagnostics.push(DiagnosticEntry {
 853                range,
 854                diagnostic: entry.diagnostic,
 855            });
 856        }
 857        drop(edits_since_save);
 858
 859        let set = DiagnosticSet::new(provider_name, sanitized_diagnostics, content);
 860        self.apply_diagnostic_update(set.clone(), cx);
 861        Ok(Operation::UpdateDiagnostics {
 862            provider_name: set.provider_name().to_string(),
 863            diagnostics: set.iter().cloned().collect(),
 864            lamport_timestamp: self.text.lamport_clock.tick(),
 865        })
 866    }
 867
 868    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 869        if let Some(indent_columns) = self.compute_autoindents() {
 870            let indent_columns = cx.background().spawn(indent_columns);
 871            match cx
 872                .background()
 873                .block_with_timeout(Duration::from_micros(500), indent_columns)
 874            {
 875                Ok(indent_columns) => self.apply_autoindents(indent_columns, cx),
 876                Err(indent_columns) => {
 877                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
 878                        let indent_columns = indent_columns.await;
 879                        this.update(&mut cx, |this, cx| {
 880                            this.apply_autoindents(indent_columns, cx);
 881                        });
 882                    }));
 883                }
 884            }
 885        }
 886    }
 887
 888    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, u32>>> {
 889        let max_rows_between_yields = 100;
 890        let snapshot = self.snapshot();
 891        if snapshot.language.is_none()
 892            || snapshot.tree.is_none()
 893            || self.autoindent_requests.is_empty()
 894        {
 895            return None;
 896        }
 897
 898        let autoindent_requests = self.autoindent_requests.clone();
 899        Some(async move {
 900            let mut indent_columns = BTreeMap::new();
 901            for request in autoindent_requests {
 902                let old_to_new_rows = request
 903                    .edited
 904                    .iter()
 905                    .map(|anchor| anchor.summary::<Point>(&request.before_edit).row)
 906                    .zip(
 907                        request
 908                            .edited
 909                            .iter()
 910                            .map(|anchor| anchor.summary::<Point>(&snapshot).row),
 911                    )
 912                    .collect::<BTreeMap<u32, u32>>();
 913
 914                let mut old_suggestions = HashMap::<u32, u32>::default();
 915                let old_edited_ranges =
 916                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
 917                for old_edited_range in old_edited_ranges {
 918                    let suggestions = request
 919                        .before_edit
 920                        .suggest_autoindents(old_edited_range.clone())
 921                        .into_iter()
 922                        .flatten();
 923                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
 924                        let indentation_basis = old_to_new_rows
 925                            .get(&suggestion.basis_row)
 926                            .and_then(|from_row| old_suggestions.get(from_row).copied())
 927                            .unwrap_or_else(|| {
 928                                request
 929                                    .before_edit
 930                                    .indent_column_for_line(suggestion.basis_row)
 931                            });
 932                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 933                        old_suggestions.insert(
 934                            *old_to_new_rows.get(&old_row).unwrap(),
 935                            indentation_basis + delta,
 936                        );
 937                    }
 938                    yield_now().await;
 939                }
 940
 941                // At this point, old_suggestions contains the suggested indentation for all edited lines with respect to the state of the
 942                // buffer before the edit, but keyed by the row for these lines after the edits were applied.
 943                let new_edited_row_ranges =
 944                    contiguous_ranges(old_to_new_rows.values().copied(), max_rows_between_yields);
 945                for new_edited_row_range in new_edited_row_ranges {
 946                    let suggestions = snapshot
 947                        .suggest_autoindents(new_edited_row_range.clone())
 948                        .into_iter()
 949                        .flatten();
 950                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
 951                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 952                        let new_indentation = indent_columns
 953                            .get(&suggestion.basis_row)
 954                            .copied()
 955                            .unwrap_or_else(|| {
 956                                snapshot.indent_column_for_line(suggestion.basis_row)
 957                            })
 958                            + delta;
 959                        if old_suggestions
 960                            .get(&new_row)
 961                            .map_or(true, |old_indentation| new_indentation != *old_indentation)
 962                        {
 963                            indent_columns.insert(new_row, new_indentation);
 964                        }
 965                    }
 966                    yield_now().await;
 967                }
 968
 969                if let Some(inserted) = request.inserted.as_ref() {
 970                    let inserted_row_ranges = contiguous_ranges(
 971                        inserted
 972                            .iter()
 973                            .map(|range| range.to_point(&snapshot))
 974                            .flat_map(|range| range.start.row..range.end.row + 1),
 975                        max_rows_between_yields,
 976                    );
 977                    for inserted_row_range in inserted_row_ranges {
 978                        let suggestions = snapshot
 979                            .suggest_autoindents(inserted_row_range.clone())
 980                            .into_iter()
 981                            .flatten();
 982                        for (row, suggestion) in inserted_row_range.zip(suggestions) {
 983                            let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 984                            let new_indentation = indent_columns
 985                                .get(&suggestion.basis_row)
 986                                .copied()
 987                                .unwrap_or_else(|| {
 988                                    snapshot.indent_column_for_line(suggestion.basis_row)
 989                                })
 990                                + delta;
 991                            indent_columns.insert(row, new_indentation);
 992                        }
 993                        yield_now().await;
 994                    }
 995                }
 996            }
 997            indent_columns
 998        })
 999    }
1000
1001    fn apply_autoindents(
1002        &mut self,
1003        indent_columns: BTreeMap<u32, u32>,
1004        cx: &mut ModelContext<Self>,
1005    ) {
1006        self.autoindent_requests.clear();
1007        self.start_transaction();
1008        for (row, indent_column) in &indent_columns {
1009            self.set_indent_column_for_line(*row, *indent_column, cx);
1010        }
1011        self.end_transaction(cx);
1012    }
1013
1014    fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
1015        let current_column = self.indent_column_for_line(row);
1016        if column > current_column {
1017            let offset = Point::new(row, 0).to_offset(&*self);
1018            self.edit(
1019                [offset..offset],
1020                " ".repeat((column - current_column) as usize),
1021                cx,
1022            );
1023        } else if column < current_column {
1024            self.edit(
1025                [Point::new(row, 0)..Point::new(row, current_column - column)],
1026                "",
1027                cx,
1028            );
1029        }
1030    }
1031
1032    pub(crate) fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
1033        // TODO: it would be nice to not allocate here.
1034        let old_text = self.text();
1035        let base_version = self.version();
1036        cx.background().spawn(async move {
1037            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1038                .iter_all_changes()
1039                .map(|c| (c.tag(), c.value().len()))
1040                .collect::<Vec<_>>();
1041            Diff {
1042                base_version,
1043                new_text,
1044                changes,
1045            }
1046        })
1047    }
1048
1049    pub(crate) fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1050        if self.version == diff.base_version {
1051            self.start_transaction();
1052            let mut offset = 0;
1053            for (tag, len) in diff.changes {
1054                let range = offset..(offset + len);
1055                match tag {
1056                    ChangeTag::Equal => offset += len,
1057                    ChangeTag::Delete => self.edit(Some(range), "", cx),
1058                    ChangeTag::Insert => {
1059                        self.edit(Some(offset..offset), &diff.new_text[range], cx);
1060                        offset += len;
1061                    }
1062                }
1063            }
1064            self.end_transaction(cx);
1065            true
1066        } else {
1067            false
1068        }
1069    }
1070
1071    pub fn is_dirty(&self) -> bool {
1072        !self.saved_version.ge(&self.version)
1073            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1074    }
1075
1076    pub fn has_conflict(&self) -> bool {
1077        !self.saved_version.ge(&self.version)
1078            && self
1079                .file
1080                .as_ref()
1081                .map_or(false, |file| file.mtime() > self.saved_mtime)
1082    }
1083
1084    pub fn subscribe(&mut self) -> Subscription {
1085        self.text.subscribe()
1086    }
1087
1088    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1089        self.start_transaction_at(Instant::now())
1090    }
1091
1092    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1093        self.text.start_transaction_at(now)
1094    }
1095
1096    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1097        self.end_transaction_at(Instant::now(), cx)
1098    }
1099
1100    pub fn end_transaction_at(
1101        &mut self,
1102        now: Instant,
1103        cx: &mut ModelContext<Self>,
1104    ) -> Option<TransactionId> {
1105        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1106            let was_dirty = start_version != self.saved_version;
1107            self.did_edit(&start_version, was_dirty, cx);
1108            Some(transaction_id)
1109        } else {
1110            None
1111        }
1112    }
1113
1114    pub fn set_active_selections(
1115        &mut self,
1116        selections: Arc<[Selection<Anchor>]>,
1117        cx: &mut ModelContext<Self>,
1118    ) {
1119        let lamport_timestamp = self.text.lamport_clock.tick();
1120        self.remote_selections
1121            .insert(self.text.replica_id(), selections.clone());
1122        self.send_operation(
1123            Operation::UpdateSelections {
1124                replica_id: self.text.replica_id(),
1125                selections,
1126                lamport_timestamp,
1127            },
1128            cx,
1129        );
1130    }
1131
1132    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1133        let lamport_timestamp = self.text.lamport_clock.tick();
1134        self.send_operation(
1135            Operation::RemoveSelections {
1136                replica_id: self.text.replica_id(),
1137                lamport_timestamp,
1138            },
1139            cx,
1140        );
1141    }
1142
1143    fn update_language_server(&mut self) {
1144        let language_server = if let Some(language_server) = self.language_server.as_mut() {
1145            language_server
1146        } else {
1147            return;
1148        };
1149        let abs_path = self
1150            .file
1151            .as_ref()
1152            .map_or(Path::new("/").to_path_buf(), |file| {
1153                file.abs_path().unwrap()
1154            });
1155
1156        let version = post_inc(&mut language_server.next_version);
1157        let snapshot = LanguageServerSnapshot {
1158            buffer_snapshot: self.text.snapshot(),
1159            version,
1160            path: Arc::from(abs_path),
1161        };
1162        language_server
1163            .pending_snapshots
1164            .insert(version, snapshot.clone());
1165        let _ = language_server
1166            .latest_snapshot
1167            .blocking_send(Some(snapshot));
1168    }
1169
1170    pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, cx: &mut ModelContext<Self>)
1171    where
1172        I: IntoIterator<Item = Range<S>>,
1173        S: ToOffset,
1174        T: Into<String>,
1175    {
1176        self.edit_internal(ranges_iter, new_text, false, cx)
1177    }
1178
1179    pub fn edit_with_autoindent<I, S, T>(
1180        &mut self,
1181        ranges_iter: I,
1182        new_text: T,
1183        cx: &mut ModelContext<Self>,
1184    ) where
1185        I: IntoIterator<Item = Range<S>>,
1186        S: ToOffset,
1187        T: Into<String>,
1188    {
1189        self.edit_internal(ranges_iter, new_text, true, cx)
1190    }
1191
1192    pub fn edit_internal<I, S, T>(
1193        &mut self,
1194        ranges_iter: I,
1195        new_text: T,
1196        autoindent: bool,
1197        cx: &mut ModelContext<Self>,
1198    ) where
1199        I: IntoIterator<Item = Range<S>>,
1200        S: ToOffset,
1201        T: Into<String>,
1202    {
1203        let new_text = new_text.into();
1204
1205        // Skip invalid ranges and coalesce contiguous ones.
1206        let mut ranges: Vec<Range<usize>> = Vec::new();
1207        for range in ranges_iter {
1208            let range = range.start.to_offset(self)..range.end.to_offset(self);
1209            if !new_text.is_empty() || !range.is_empty() {
1210                if let Some(prev_range) = ranges.last_mut() {
1211                    if prev_range.end >= range.start {
1212                        prev_range.end = cmp::max(prev_range.end, range.end);
1213                    } else {
1214                        ranges.push(range);
1215                    }
1216                } else {
1217                    ranges.push(range);
1218                }
1219            }
1220        }
1221        if ranges.is_empty() {
1222            return;
1223        }
1224
1225        self.start_transaction();
1226        self.pending_autoindent.take();
1227        let autoindent_request = if autoindent && self.language.is_some() {
1228            let before_edit = self.snapshot();
1229            let edited = ranges
1230                .iter()
1231                .filter_map(|range| {
1232                    let start = range.start.to_point(self);
1233                    if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1234                        None
1235                    } else {
1236                        Some(self.anchor_before(range.start))
1237                    }
1238                })
1239                .collect();
1240            Some((before_edit, edited))
1241        } else {
1242            None
1243        };
1244
1245        let first_newline_ix = new_text.find('\n');
1246        let new_text_len = new_text.len();
1247
1248        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1249
1250        if let Some((before_edit, edited)) = autoindent_request {
1251            let mut inserted = None;
1252            if let Some(first_newline_ix) = first_newline_ix {
1253                let mut delta = 0isize;
1254                inserted = Some(
1255                    ranges
1256                        .iter()
1257                        .map(|range| {
1258                            let start =
1259                                (delta + range.start as isize) as usize + first_newline_ix + 1;
1260                            let end = (delta + range.start as isize) as usize + new_text_len;
1261                            delta +=
1262                                (range.end as isize - range.start as isize) + new_text_len as isize;
1263                            self.anchor_before(start)..self.anchor_after(end)
1264                        })
1265                        .collect(),
1266                );
1267            }
1268
1269            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1270                before_edit,
1271                edited,
1272                inserted,
1273            }));
1274        }
1275
1276        self.end_transaction(cx);
1277        self.send_operation(Operation::Buffer(text::Operation::Edit(edit)), cx);
1278    }
1279
1280    fn did_edit(
1281        &mut self,
1282        old_version: &clock::Global,
1283        was_dirty: bool,
1284        cx: &mut ModelContext<Self>,
1285    ) {
1286        if self.edits_since::<usize>(old_version).next().is_none() {
1287            return;
1288        }
1289
1290        self.reparse(cx);
1291        self.update_language_server();
1292
1293        cx.emit(Event::Edited);
1294        if !was_dirty {
1295            cx.emit(Event::Dirtied);
1296        }
1297        cx.notify();
1298    }
1299
1300    fn grammar(&self) -> Option<&Arc<Grammar>> {
1301        self.language.as_ref().and_then(|l| l.grammar.as_ref())
1302    }
1303
1304    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1305        &mut self,
1306        ops: I,
1307        cx: &mut ModelContext<Self>,
1308    ) -> Result<()> {
1309        self.pending_autoindent.take();
1310        let was_dirty = self.is_dirty();
1311        let old_version = self.version.clone();
1312        let mut deferred_ops = Vec::new();
1313        let buffer_ops = ops
1314            .into_iter()
1315            .filter_map(|op| match op {
1316                Operation::Buffer(op) => Some(op),
1317                _ => {
1318                    if self.can_apply_op(&op) {
1319                        self.apply_op(op, cx);
1320                    } else {
1321                        deferred_ops.push(op);
1322                    }
1323                    None
1324                }
1325            })
1326            .collect::<Vec<_>>();
1327        self.text.apply_ops(buffer_ops)?;
1328        self.flush_deferred_ops(cx);
1329        self.did_edit(&old_version, was_dirty, cx);
1330        // Notify independently of whether the buffer was edited as the operations could include a
1331        // selection update.
1332        cx.notify();
1333        Ok(())
1334    }
1335
1336    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1337        let mut deferred_ops = Vec::new();
1338        for op in self.deferred_ops.drain().iter().cloned() {
1339            if self.can_apply_op(&op) {
1340                self.apply_op(op, cx);
1341            } else {
1342                deferred_ops.push(op);
1343            }
1344        }
1345        self.deferred_ops.insert(deferred_ops);
1346    }
1347
1348    fn can_apply_op(&self, operation: &Operation) -> bool {
1349        match operation {
1350            Operation::Buffer(_) => {
1351                unreachable!("buffer operations should never be applied at this layer")
1352            }
1353            Operation::UpdateDiagnostics {
1354                diagnostics: diagnostic_set,
1355                ..
1356            } => diagnostic_set.iter().all(|diagnostic| {
1357                self.text.can_resolve(&diagnostic.range.start)
1358                    && self.text.can_resolve(&diagnostic.range.end)
1359            }),
1360            Operation::UpdateSelections { selections, .. } => selections
1361                .iter()
1362                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1363            Operation::RemoveSelections { .. } => true,
1364        }
1365    }
1366
1367    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1368        match operation {
1369            Operation::Buffer(_) => {
1370                unreachable!("buffer operations should never be applied at this layer")
1371            }
1372            Operation::UpdateDiagnostics {
1373                provider_name,
1374                diagnostics: diagnostic_set,
1375                ..
1376            } => {
1377                let snapshot = self.snapshot();
1378                self.apply_diagnostic_update(
1379                    DiagnosticSet::from_sorted_entries(
1380                        provider_name,
1381                        diagnostic_set.iter().cloned(),
1382                        &snapshot,
1383                    ),
1384                    cx,
1385                );
1386            }
1387            Operation::UpdateSelections {
1388                replica_id,
1389                selections,
1390                lamport_timestamp,
1391            } => {
1392                self.remote_selections.insert(replica_id, selections);
1393                self.text.lamport_clock.observe(lamport_timestamp);
1394                self.selections_update_count += 1;
1395            }
1396            Operation::RemoveSelections {
1397                replica_id,
1398                lamport_timestamp,
1399            } => {
1400                self.remote_selections.remove(&replica_id);
1401                self.text.lamport_clock.observe(lamport_timestamp);
1402                self.selections_update_count += 1;
1403            }
1404        }
1405    }
1406
1407    fn apply_diagnostic_update(&mut self, set: DiagnosticSet, cx: &mut ModelContext<Self>) {
1408        match self
1409            .diagnostic_sets
1410            .binary_search_by_key(&set.provider_name(), |set| set.provider_name())
1411        {
1412            Ok(ix) => self.diagnostic_sets[ix] = set.clone(),
1413            Err(ix) => self.diagnostic_sets.insert(ix, set.clone()),
1414        }
1415
1416        self.diagnostics_update_count += 1;
1417        cx.notify();
1418        cx.emit(Event::DiagnosticsUpdated);
1419    }
1420
1421    #[cfg(not(test))]
1422    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1423        if let Some(file) = &self.file {
1424            file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1425        }
1426    }
1427
1428    #[cfg(test)]
1429    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1430        self.operations.push(operation);
1431    }
1432
1433    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1434        self.remote_selections.remove(&replica_id);
1435        cx.notify();
1436    }
1437
1438    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1439        let was_dirty = self.is_dirty();
1440        let old_version = self.version.clone();
1441
1442        if let Some((transaction_id, operation)) = self.text.undo() {
1443            self.send_operation(Operation::Buffer(operation), cx);
1444            self.did_edit(&old_version, was_dirty, cx);
1445            Some(transaction_id)
1446        } else {
1447            None
1448        }
1449    }
1450
1451    pub fn undo_transaction(
1452        &mut self,
1453        transaction_id: TransactionId,
1454        cx: &mut ModelContext<Self>,
1455    ) -> bool {
1456        let was_dirty = self.is_dirty();
1457        let old_version = self.version.clone();
1458
1459        if let Some(operation) = self.text.undo_transaction(transaction_id) {
1460            self.send_operation(Operation::Buffer(operation), cx);
1461            self.did_edit(&old_version, was_dirty, cx);
1462            true
1463        } else {
1464            false
1465        }
1466    }
1467
1468    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1469        let was_dirty = self.is_dirty();
1470        let old_version = self.version.clone();
1471
1472        if let Some((transaction_id, operation)) = self.text.redo() {
1473            self.send_operation(Operation::Buffer(operation), cx);
1474            self.did_edit(&old_version, was_dirty, cx);
1475            Some(transaction_id)
1476        } else {
1477            None
1478        }
1479    }
1480
1481    pub fn redo_transaction(
1482        &mut self,
1483        transaction_id: TransactionId,
1484        cx: &mut ModelContext<Self>,
1485    ) -> bool {
1486        let was_dirty = self.is_dirty();
1487        let old_version = self.version.clone();
1488
1489        if let Some(operation) = self.text.redo_transaction(transaction_id) {
1490            self.send_operation(Operation::Buffer(operation), cx);
1491            self.did_edit(&old_version, was_dirty, cx);
1492            true
1493        } else {
1494            false
1495        }
1496    }
1497}
1498
1499#[cfg(any(test, feature = "test-support"))]
1500impl Buffer {
1501    pub fn randomly_edit<T>(
1502        &mut self,
1503        rng: &mut T,
1504        old_range_count: usize,
1505        cx: &mut ModelContext<Self>,
1506    ) where
1507        T: rand::Rng,
1508    {
1509        self.start_transaction();
1510        self.text.randomly_edit(rng, old_range_count);
1511        self.end_transaction(cx);
1512    }
1513}
1514
1515impl Entity for Buffer {
1516    type Event = Event;
1517
1518    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1519        if let Some(file) = self.file.as_ref() {
1520            file.buffer_removed(self.remote_id(), cx);
1521        }
1522    }
1523}
1524
1525impl Deref for Buffer {
1526    type Target = TextBuffer;
1527
1528    fn deref(&self) -> &Self::Target {
1529        &self.text
1530    }
1531}
1532
1533impl BufferSnapshot {
1534    fn suggest_autoindents<'a>(
1535        &'a self,
1536        row_range: Range<u32>,
1537    ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1538        let mut query_cursor = QueryCursorHandle::new();
1539        if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1540            let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1541
1542            // Get the "indentation ranges" that intersect this row range.
1543            let indent_capture_ix = grammar.indents_query.capture_index_for_name("indent");
1544            let end_capture_ix = grammar.indents_query.capture_index_for_name("end");
1545            query_cursor.set_point_range(
1546                Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1547                    ..Point::new(row_range.end, 0).to_ts_point(),
1548            );
1549            let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1550            for mat in query_cursor.matches(
1551                &grammar.indents_query,
1552                tree.root_node(),
1553                TextProvider(self.as_rope()),
1554            ) {
1555                let mut node_kind = "";
1556                let mut start: Option<Point> = None;
1557                let mut end: Option<Point> = None;
1558                for capture in mat.captures {
1559                    if Some(capture.index) == indent_capture_ix {
1560                        node_kind = capture.node.kind();
1561                        start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1562                        end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1563                    } else if Some(capture.index) == end_capture_ix {
1564                        end = Some(Point::from_ts_point(capture.node.start_position().into()));
1565                    }
1566                }
1567
1568                if let Some((start, end)) = start.zip(end) {
1569                    if start.row == end.row {
1570                        continue;
1571                    }
1572
1573                    let range = start..end;
1574                    match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1575                        Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1576                        Ok(ix) => {
1577                            let prev_range = &mut indentation_ranges[ix];
1578                            prev_range.0.end = prev_range.0.end.max(range.end);
1579                        }
1580                    }
1581                }
1582            }
1583
1584            let mut prev_row = prev_non_blank_row.unwrap_or(0);
1585            Some(row_range.map(move |row| {
1586                let row_start = Point::new(row, self.indent_column_for_line(row));
1587
1588                let mut indent_from_prev_row = false;
1589                let mut outdent_to_row = u32::MAX;
1590                for (range, _node_kind) in &indentation_ranges {
1591                    if range.start.row >= row {
1592                        break;
1593                    }
1594
1595                    if range.start.row == prev_row && range.end > row_start {
1596                        indent_from_prev_row = true;
1597                    }
1598                    if range.end.row >= prev_row && range.end <= row_start {
1599                        outdent_to_row = outdent_to_row.min(range.start.row);
1600                    }
1601                }
1602
1603                let suggestion = if outdent_to_row == prev_row {
1604                    IndentSuggestion {
1605                        basis_row: prev_row,
1606                        indent: false,
1607                    }
1608                } else if indent_from_prev_row {
1609                    IndentSuggestion {
1610                        basis_row: prev_row,
1611                        indent: true,
1612                    }
1613                } else if outdent_to_row < prev_row {
1614                    IndentSuggestion {
1615                        basis_row: outdent_to_row,
1616                        indent: false,
1617                    }
1618                } else {
1619                    IndentSuggestion {
1620                        basis_row: prev_row,
1621                        indent: false,
1622                    }
1623                };
1624
1625                prev_row = row;
1626                suggestion
1627            }))
1628        } else {
1629            None
1630        }
1631    }
1632
1633    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1634        while row > 0 {
1635            row -= 1;
1636            if !self.is_line_blank(row) {
1637                return Some(row);
1638            }
1639        }
1640        None
1641    }
1642
1643    pub fn chunks<'a, T: ToOffset>(
1644        &'a self,
1645        range: Range<T>,
1646        theme: Option<&'a SyntaxTheme>,
1647    ) -> BufferChunks<'a> {
1648        let range = range.start.to_offset(self)..range.end.to_offset(self);
1649
1650        let mut highlights = None;
1651        let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1652        if let Some(theme) = theme {
1653            for (_, entry) in self.diagnostics_in_range::<_, usize>(range.clone()) {
1654                diagnostic_endpoints.push(DiagnosticEndpoint {
1655                    offset: entry.range.start,
1656                    is_start: true,
1657                    severity: entry.diagnostic.severity,
1658                });
1659                diagnostic_endpoints.push(DiagnosticEndpoint {
1660                    offset: entry.range.end,
1661                    is_start: false,
1662                    severity: entry.diagnostic.severity,
1663                });
1664            }
1665            diagnostic_endpoints
1666                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1667
1668            if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1669                let mut query_cursor = QueryCursorHandle::new();
1670
1671                // TODO - add a Tree-sitter API to remove the need for this.
1672                let cursor = unsafe {
1673                    std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
1674                };
1675                let captures = cursor.set_byte_range(range.clone()).captures(
1676                    &grammar.highlights_query,
1677                    tree.root_node(),
1678                    TextProvider(self.text.as_rope()),
1679                );
1680                highlights = Some(BufferChunkHighlights {
1681                    captures,
1682                    next_capture: None,
1683                    stack: Default::default(),
1684                    highlight_map: grammar.highlight_map(),
1685                    _query_cursor: query_cursor,
1686                    theme,
1687                })
1688            }
1689        }
1690
1691        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1692        let chunks = self.text.as_rope().chunks_in_range(range.clone());
1693
1694        BufferChunks {
1695            range,
1696            chunks,
1697            diagnostic_endpoints,
1698            error_depth: 0,
1699            warning_depth: 0,
1700            information_depth: 0,
1701            hint_depth: 0,
1702            highlights,
1703        }
1704    }
1705
1706    pub fn language(&self) -> Option<&Arc<Language>> {
1707        self.language.as_ref()
1708    }
1709
1710    fn grammar(&self) -> Option<&Arc<Grammar>> {
1711        self.language
1712            .as_ref()
1713            .and_then(|language| language.grammar.as_ref())
1714    }
1715
1716    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1717        if let Some(tree) = self.tree.as_ref() {
1718            let root = tree.root_node();
1719            let range = range.start.to_offset(self)..range.end.to_offset(self);
1720            let mut node = root.descendant_for_byte_range(range.start, range.end);
1721            while node.map_or(false, |n| n.byte_range() == range) {
1722                node = node.unwrap().parent();
1723            }
1724            node.map(|n| n.byte_range())
1725        } else {
1726            None
1727        }
1728    }
1729
1730    pub fn enclosing_bracket_ranges<T: ToOffset>(
1731        &self,
1732        range: Range<T>,
1733    ) -> Option<(Range<usize>, Range<usize>)> {
1734        let (grammar, tree) = self.grammar().zip(self.tree.as_ref())?;
1735        let open_capture_ix = grammar.brackets_query.capture_index_for_name("open")?;
1736        let close_capture_ix = grammar.brackets_query.capture_index_for_name("close")?;
1737
1738        // Find bracket pairs that *inclusively* contain the given range.
1739        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
1740        let mut cursor = QueryCursorHandle::new();
1741        let matches = cursor.set_byte_range(range).matches(
1742            &grammar.brackets_query,
1743            tree.root_node(),
1744            TextProvider(self.as_rope()),
1745        );
1746
1747        // Get the ranges of the innermost pair of brackets.
1748        matches
1749            .filter_map(|mat| {
1750                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
1751                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
1752                Some((open.byte_range(), close.byte_range()))
1753            })
1754            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
1755    }
1756
1757    pub fn remote_selections_in_range<'a>(
1758        &'a self,
1759        range: Range<Anchor>,
1760    ) -> impl 'a + Iterator<Item = (ReplicaId, impl 'a + Iterator<Item = &'a Selection<Anchor>>)>
1761    {
1762        self.remote_selections
1763            .iter()
1764            .filter(|(replica_id, _)| **replica_id != self.text.replica_id())
1765            .map(move |(replica_id, selections)| {
1766                let start_ix = match selections
1767                    .binary_search_by(|probe| probe.end.cmp(&range.start, self).unwrap())
1768                {
1769                    Ok(ix) | Err(ix) => ix,
1770                };
1771                let end_ix = match selections
1772                    .binary_search_by(|probe| probe.start.cmp(&range.end, self).unwrap())
1773                {
1774                    Ok(ix) | Err(ix) => ix,
1775                };
1776
1777                (*replica_id, selections[start_ix..end_ix].iter())
1778            })
1779    }
1780
1781    pub fn diagnostics_in_range<'a, T, O>(
1782        &'a self,
1783        search_range: Range<T>,
1784    ) -> impl 'a + Iterator<Item = (&'a str, DiagnosticEntry<O>)>
1785    where
1786        T: 'a + Clone + ToOffset,
1787        O: 'a + FromAnchor,
1788    {
1789        self.diagnostic_sets.iter().flat_map(move |set| {
1790            set.range(search_range.clone(), self, true)
1791                .map(|e| (set.provider_name(), e))
1792        })
1793    }
1794
1795    pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
1796        let mut groups = Vec::new();
1797        for set in &self.diagnostic_sets {
1798            set.groups(&mut groups, self);
1799        }
1800        groups
1801    }
1802
1803    pub fn diagnostic_group<'a, O>(
1804        &'a self,
1805        provider_name: &str,
1806        group_id: usize,
1807    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
1808    where
1809        O: 'a + FromAnchor,
1810    {
1811        self.diagnostic_sets
1812            .iter()
1813            .find(|s| s.provider_name() == provider_name)
1814            .into_iter()
1815            .flat_map(move |s| s.group(group_id, self))
1816    }
1817
1818    pub fn diagnostics_update_count(&self) -> usize {
1819        self.diagnostics_update_count
1820    }
1821
1822    pub fn parse_count(&self) -> usize {
1823        self.parse_count
1824    }
1825
1826    pub fn selections_update_count(&self) -> usize {
1827        self.selections_update_count
1828    }
1829}
1830
1831impl Clone for BufferSnapshot {
1832    fn clone(&self) -> Self {
1833        Self {
1834            text: self.text.clone(),
1835            tree: self.tree.clone(),
1836            remote_selections: self.remote_selections.clone(),
1837            selections_update_count: self.selections_update_count,
1838            diagnostic_sets: self.diagnostic_sets.clone(),
1839            diagnostics_update_count: self.diagnostics_update_count,
1840            is_parsing: self.is_parsing,
1841            language: self.language.clone(),
1842            parse_count: self.parse_count,
1843        }
1844    }
1845}
1846
1847impl Deref for BufferSnapshot {
1848    type Target = text::BufferSnapshot;
1849
1850    fn deref(&self) -> &Self::Target {
1851        &self.text
1852    }
1853}
1854
1855impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
1856    type I = ByteChunks<'a>;
1857
1858    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
1859        ByteChunks(self.0.chunks_in_range(node.byte_range()))
1860    }
1861}
1862
1863struct ByteChunks<'a>(rope::Chunks<'a>);
1864
1865impl<'a> Iterator for ByteChunks<'a> {
1866    type Item = &'a [u8];
1867
1868    fn next(&mut self) -> Option<Self::Item> {
1869        self.0.next().map(str::as_bytes)
1870    }
1871}
1872
1873unsafe impl<'a> Send for BufferChunks<'a> {}
1874
1875impl<'a> BufferChunks<'a> {
1876    pub fn seek(&mut self, offset: usize) {
1877        self.range.start = offset;
1878        self.chunks.seek(self.range.start);
1879        if let Some(highlights) = self.highlights.as_mut() {
1880            highlights
1881                .stack
1882                .retain(|(end_offset, _)| *end_offset > offset);
1883            if let Some((mat, capture_ix)) = &highlights.next_capture {
1884                let capture = mat.captures[*capture_ix as usize];
1885                if offset >= capture.node.start_byte() {
1886                    let next_capture_end = capture.node.end_byte();
1887                    if offset < next_capture_end {
1888                        highlights.stack.push((
1889                            next_capture_end,
1890                            highlights.highlight_map.get(capture.index),
1891                        ));
1892                    }
1893                    highlights.next_capture.take();
1894                }
1895            }
1896            highlights.captures.set_byte_range(self.range.clone());
1897        }
1898    }
1899
1900    pub fn offset(&self) -> usize {
1901        self.range.start
1902    }
1903
1904    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
1905        let depth = match endpoint.severity {
1906            DiagnosticSeverity::ERROR => &mut self.error_depth,
1907            DiagnosticSeverity::WARNING => &mut self.warning_depth,
1908            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
1909            DiagnosticSeverity::HINT => &mut self.hint_depth,
1910            _ => return,
1911        };
1912        if endpoint.is_start {
1913            *depth += 1;
1914        } else {
1915            *depth -= 1;
1916        }
1917    }
1918
1919    fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
1920        if self.error_depth > 0 {
1921            Some(DiagnosticSeverity::ERROR)
1922        } else if self.warning_depth > 0 {
1923            Some(DiagnosticSeverity::WARNING)
1924        } else if self.information_depth > 0 {
1925            Some(DiagnosticSeverity::INFORMATION)
1926        } else if self.hint_depth > 0 {
1927            Some(DiagnosticSeverity::HINT)
1928        } else {
1929            None
1930        }
1931    }
1932}
1933
1934impl<'a> Iterator for BufferChunks<'a> {
1935    type Item = Chunk<'a>;
1936
1937    fn next(&mut self) -> Option<Self::Item> {
1938        let mut next_capture_start = usize::MAX;
1939        let mut next_diagnostic_endpoint = usize::MAX;
1940
1941        if let Some(highlights) = self.highlights.as_mut() {
1942            while let Some((parent_capture_end, _)) = highlights.stack.last() {
1943                if *parent_capture_end <= self.range.start {
1944                    highlights.stack.pop();
1945                } else {
1946                    break;
1947                }
1948            }
1949
1950            if highlights.next_capture.is_none() {
1951                highlights.next_capture = highlights.captures.next();
1952            }
1953
1954            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
1955                let capture = mat.captures[*capture_ix as usize];
1956                if self.range.start < capture.node.start_byte() {
1957                    next_capture_start = capture.node.start_byte();
1958                    break;
1959                } else {
1960                    let highlight_id = highlights.highlight_map.get(capture.index);
1961                    highlights
1962                        .stack
1963                        .push((capture.node.end_byte(), highlight_id));
1964                    highlights.next_capture = highlights.captures.next();
1965                }
1966            }
1967        }
1968
1969        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
1970            if endpoint.offset <= self.range.start {
1971                self.update_diagnostic_depths(endpoint);
1972                self.diagnostic_endpoints.next();
1973            } else {
1974                next_diagnostic_endpoint = endpoint.offset;
1975                break;
1976            }
1977        }
1978
1979        if let Some(chunk) = self.chunks.peek() {
1980            let chunk_start = self.range.start;
1981            let mut chunk_end = (self.chunks.offset() + chunk.len())
1982                .min(next_capture_start)
1983                .min(next_diagnostic_endpoint);
1984            let mut highlight_style = None;
1985            if let Some(highlights) = self.highlights.as_ref() {
1986                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
1987                    chunk_end = chunk_end.min(*parent_capture_end);
1988                    highlight_style = parent_highlight_id.style(highlights.theme);
1989                }
1990            }
1991
1992            let slice =
1993                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
1994            self.range.start = chunk_end;
1995            if self.range.start == self.chunks.offset() + chunk.len() {
1996                self.chunks.next().unwrap();
1997            }
1998
1999            Some(Chunk {
2000                text: slice,
2001                highlight_style,
2002                diagnostic: self.current_diagnostic_severity(),
2003            })
2004        } else {
2005            None
2006        }
2007    }
2008}
2009
2010impl QueryCursorHandle {
2011    fn new() -> Self {
2012        QueryCursorHandle(Some(
2013            QUERY_CURSORS
2014                .lock()
2015                .pop()
2016                .unwrap_or_else(|| QueryCursor::new()),
2017        ))
2018    }
2019}
2020
2021impl Deref for QueryCursorHandle {
2022    type Target = QueryCursor;
2023
2024    fn deref(&self) -> &Self::Target {
2025        self.0.as_ref().unwrap()
2026    }
2027}
2028
2029impl DerefMut for QueryCursorHandle {
2030    fn deref_mut(&mut self) -> &mut Self::Target {
2031        self.0.as_mut().unwrap()
2032    }
2033}
2034
2035impl Drop for QueryCursorHandle {
2036    fn drop(&mut self) {
2037        let mut cursor = self.0.take().unwrap();
2038        cursor.set_byte_range(0..usize::MAX);
2039        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
2040        QUERY_CURSORS.lock().push(cursor)
2041    }
2042}
2043
2044trait ToTreeSitterPoint {
2045    fn to_ts_point(self) -> tree_sitter::Point;
2046    fn from_ts_point(point: tree_sitter::Point) -> Self;
2047}
2048
2049impl ToTreeSitterPoint for Point {
2050    fn to_ts_point(self) -> tree_sitter::Point {
2051        tree_sitter::Point::new(self.row as usize, self.column as usize)
2052    }
2053
2054    fn from_ts_point(point: tree_sitter::Point) -> Self {
2055        Point::new(point.row as u32, point.column as u32)
2056    }
2057}
2058
2059impl operation_queue::Operation for Operation {
2060    fn lamport_timestamp(&self) -> clock::Lamport {
2061        match self {
2062            Operation::Buffer(_) => {
2063                unreachable!("buffer operations should never be deferred at this layer")
2064            }
2065            Operation::UpdateDiagnostics {
2066                lamport_timestamp, ..
2067            }
2068            | Operation::UpdateSelections {
2069                lamport_timestamp, ..
2070            }
2071            | Operation::RemoveSelections {
2072                lamport_timestamp, ..
2073            } => *lamport_timestamp,
2074        }
2075    }
2076}
2077
2078impl Default for Diagnostic {
2079    fn default() -> Self {
2080        Self {
2081            code: Default::default(),
2082            severity: DiagnosticSeverity::ERROR,
2083            message: Default::default(),
2084            group_id: Default::default(),
2085            is_primary: Default::default(),
2086            is_valid: true,
2087            is_disk_based: false,
2088        }
2089    }
2090}
2091
2092pub fn contiguous_ranges(
2093    values: impl Iterator<Item = u32>,
2094    max_len: usize,
2095) -> impl Iterator<Item = Range<u32>> {
2096    let mut values = values.into_iter();
2097    let mut current_range: Option<Range<u32>> = None;
2098    std::iter::from_fn(move || loop {
2099        if let Some(value) = values.next() {
2100            if let Some(range) = &mut current_range {
2101                if value == range.end && range.len() < max_len {
2102                    range.end += 1;
2103                    continue;
2104                }
2105            }
2106
2107            let prev_range = current_range.clone();
2108            current_range = Some(value..(value + 1));
2109            if prev_range.is_some() {
2110                return prev_range;
2111            }
2112        } else {
2113            return current_range.take();
2114        }
2115    })
2116}