lib.rs

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