lib.rs

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