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