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