1pub use crate::{
2 diagnostic_set::DiagnosticSet,
3 highlight_map::{HighlightId, HighlightMap},
4 proto, BracketPair, Grammar, Language, LanguageConfig, LanguageRegistry, LanguageServerConfig,
5 PLAIN_TEXT,
6};
7use crate::{
8 diagnostic_set::{DiagnosticEntry, DiagnosticGroup},
9 outline::OutlineItem,
10 range_from_lsp, Outline, ToLspPosition,
11};
12use anyhow::{anyhow, Result};
13use clock::ReplicaId;
14use futures::FutureExt as _;
15use gpui::{fonts::HighlightStyle, 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::{self, Ordering},
26 collections::{BTreeMap, HashMap},
27 ffi::OsString,
28 future::Future,
29 iter::{Iterator, Peekable},
30 ops::{Deref, DerefMut, Range, Sub},
31 path::{Path, PathBuf},
32 str,
33 sync::Arc,
34 time::{Duration, Instant, SystemTime, UNIX_EPOCH},
35 vec,
36};
37use sum_tree::TreeMap;
38use text::{operation_queue::OperationQueue, rope::TextDimension};
39pub use text::{Buffer as TextBuffer, Operation as _, *};
40use theme::SyntaxTheme;
41use tree_sitter::{InputEdit, Parser, QueryCursor, Tree};
42use util::{post_inc, TryFutureExt as _};
43
44#[cfg(any(test, feature = "test-support"))]
45pub use tree_sitter_rust;
46
47pub use lsp::DiagnosticSeverity;
48
49thread_local! {
50 static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
51}
52
53lazy_static! {
54 static ref QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Default::default();
55}
56
57// TODO - Make this configurable
58const INDENT_SIZE: u32 = 4;
59
60pub struct Buffer {
61 text: TextBuffer,
62 file: Option<Box<dyn File>>,
63 saved_version: clock::Global,
64 saved_mtime: SystemTime,
65 language: Option<Arc<Language>>,
66 autoindent_requests: Vec<Arc<AutoindentRequest>>,
67 pending_autoindent: Option<Task<()>>,
68 sync_parse_timeout: Duration,
69 syntax_tree: Mutex<Option<SyntaxTree>>,
70 parsing_in_background: bool,
71 parse_count: usize,
72 diagnostics: DiagnosticSet,
73 remote_selections: TreeMap<ReplicaId, SelectionSet>,
74 selections_update_count: usize,
75 diagnostics_update_count: usize,
76 language_server: Option<LanguageServerState>,
77 completion_triggers: Vec<String>,
78 deferred_ops: OperationQueue<Operation>,
79 #[cfg(test)]
80 pub(crate) operations: Vec<Operation>,
81}
82
83pub struct BufferSnapshot {
84 text: text::BufferSnapshot,
85 tree: Option<Tree>,
86 diagnostics: DiagnosticSet,
87 diagnostics_update_count: usize,
88 remote_selections: TreeMap<ReplicaId, SelectionSet>,
89 selections_update_count: usize,
90 is_parsing: bool,
91 language: Option<Arc<Language>>,
92 parse_count: usize,
93}
94
95#[derive(Clone, Debug)]
96struct SelectionSet {
97 selections: Arc<[Selection<Anchor>]>,
98 lamport_timestamp: clock::Lamport,
99}
100
101#[derive(Clone, Debug, PartialEq, Eq)]
102pub struct GroupId {
103 source: Arc<str>,
104 id: usize,
105}
106
107#[derive(Clone, Debug, PartialEq, Eq)]
108pub struct Diagnostic {
109 pub code: Option<String>,
110 pub severity: DiagnosticSeverity,
111 pub message: String,
112 pub group_id: usize,
113 pub is_valid: bool,
114 pub is_primary: bool,
115 pub is_disk_based: bool,
116}
117
118#[derive(Clone, Debug)]
119pub struct Completion<T> {
120 pub old_range: Range<T>,
121 pub new_text: String,
122 pub lsp_completion: lsp::CompletionItem,
123}
124
125struct LanguageServerState {
126 server: Arc<LanguageServer>,
127 latest_snapshot: watch::Sender<Option<LanguageServerSnapshot>>,
128 pending_snapshots: BTreeMap<usize, LanguageServerSnapshot>,
129 next_version: usize,
130 _maintain_server: Task<()>,
131}
132
133#[derive(Clone)]
134struct LanguageServerSnapshot {
135 buffer_snapshot: text::BufferSnapshot,
136 version: usize,
137 path: Arc<Path>,
138}
139
140#[derive(Clone, Debug)]
141pub enum Operation {
142 Buffer(text::Operation),
143 UpdateDiagnostics {
144 diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
145 lamport_timestamp: clock::Lamport,
146 },
147 UpdateSelections {
148 replica_id: ReplicaId,
149 selections: Arc<[Selection<Anchor>]>,
150 lamport_timestamp: clock::Lamport,
151 },
152 UpdateCompletionTriggers {
153 triggers: Vec<String>,
154 },
155}
156
157#[derive(Clone, Debug, Eq, PartialEq)]
158pub enum Event {
159 Edited,
160 Dirtied,
161 Saved,
162 FileHandleChanged,
163 Reloaded,
164 Reparsed,
165 DiagnosticsUpdated,
166 Closed,
167}
168
169pub trait File {
170 fn as_local(&self) -> Option<&dyn LocalFile>;
171
172 fn is_local(&self) -> bool {
173 self.as_local().is_some()
174 }
175
176 fn mtime(&self) -> SystemTime;
177
178 /// Returns the path of this file relative to the worktree's root directory.
179 fn path(&self) -> &Arc<Path>;
180
181 /// Returns the path of this file relative to the worktree's parent directory (this means it
182 /// includes the name of the worktree's root folder).
183 fn full_path(&self, cx: &AppContext) -> PathBuf;
184
185 /// Returns the last component of this handle's absolute path. If this handle refers to the root
186 /// of its worktree, then this method will return the name of the worktree itself.
187 fn file_name(&self, cx: &AppContext) -> OsString;
188
189 fn is_deleted(&self) -> bool;
190
191 fn save(
192 &self,
193 buffer_id: u64,
194 text: Rope,
195 version: clock::Global,
196 cx: &mut MutableAppContext,
197 ) -> Task<Result<(clock::Global, SystemTime)>>;
198
199 fn format_remote(&self, buffer_id: u64, cx: &mut MutableAppContext)
200 -> Option<Task<Result<()>>>;
201
202 fn completions(
203 &self,
204 buffer_id: u64,
205 position: Anchor,
206 cx: &mut MutableAppContext,
207 ) -> Task<Result<Vec<Completion<Anchor>>>>;
208
209 fn apply_additional_edits_for_completion(
210 &self,
211 buffer_id: u64,
212 completion: Completion<Anchor>,
213 cx: &mut MutableAppContext,
214 ) -> Task<Result<Vec<clock::Local>>>;
215
216 fn buffer_updated(&self, buffer_id: u64, operation: Operation, cx: &mut MutableAppContext);
217
218 fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext);
219
220 fn as_any(&self) -> &dyn Any;
221
222 fn to_proto(&self) -> rpc::proto::File;
223}
224
225pub trait LocalFile: File {
226 /// Returns the absolute path of this file.
227 fn abs_path(&self, cx: &AppContext) -> PathBuf;
228
229 fn load(&self, cx: &AppContext) -> Task<Result<String>>;
230
231 fn buffer_reloaded(
232 &self,
233 buffer_id: u64,
234 version: &clock::Global,
235 mtime: SystemTime,
236 cx: &mut MutableAppContext,
237 );
238}
239
240#[cfg(feature = "test-support")]
241pub struct FakeFile {
242 pub path: Arc<Path>,
243}
244
245#[cfg(feature = "test-support")]
246impl File for FakeFile {
247 fn as_local(&self) -> Option<&dyn LocalFile> {
248 Some(self)
249 }
250
251 fn mtime(&self) -> SystemTime {
252 SystemTime::UNIX_EPOCH
253 }
254
255 fn path(&self) -> &Arc<Path> {
256 &self.path
257 }
258
259 fn full_path(&self, _: &AppContext) -> PathBuf {
260 self.path.to_path_buf()
261 }
262
263 fn file_name(&self, _: &AppContext) -> OsString {
264 self.path.file_name().unwrap().to_os_string()
265 }
266
267 fn is_deleted(&self) -> bool {
268 false
269 }
270
271 fn save(
272 &self,
273 _: u64,
274 _: Rope,
275 _: clock::Global,
276 cx: &mut MutableAppContext,
277 ) -> Task<Result<(clock::Global, SystemTime)>> {
278 cx.spawn(|_| async move { Ok((Default::default(), SystemTime::UNIX_EPOCH)) })
279 }
280
281 fn format_remote(&self, _: u64, _: &mut MutableAppContext) -> Option<Task<Result<()>>> {
282 None
283 }
284
285 fn completions(
286 &self,
287 _: u64,
288 _: Anchor,
289 _: &mut MutableAppContext,
290 ) -> Task<Result<Vec<Completion<Anchor>>>> {
291 Task::ready(Ok(Default::default()))
292 }
293
294 fn apply_additional_edits_for_completion(
295 &self,
296 _: u64,
297 _: Completion<Anchor>,
298 _: &mut MutableAppContext,
299 ) -> Task<Result<Vec<clock::Local>>> {
300 Task::ready(Ok(Default::default()))
301 }
302
303 fn buffer_updated(&self, _: u64, _: Operation, _: &mut MutableAppContext) {}
304
305 fn buffer_removed(&self, _: u64, _: &mut MutableAppContext) {}
306
307 fn as_any(&self) -> &dyn Any {
308 self
309 }
310
311 fn to_proto(&self) -> rpc::proto::File {
312 unimplemented!()
313 }
314}
315
316#[cfg(feature = "test-support")]
317impl LocalFile for FakeFile {
318 fn abs_path(&self, _: &AppContext) -> PathBuf {
319 self.path.to_path_buf()
320 }
321
322 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
323 cx.background().spawn(async move { Ok(Default::default()) })
324 }
325
326 fn buffer_reloaded(&self, _: u64, _: &clock::Global, _: SystemTime, _: &mut MutableAppContext) {
327 }
328}
329
330pub(crate) struct QueryCursorHandle(Option<QueryCursor>);
331
332#[derive(Clone)]
333struct SyntaxTree {
334 tree: Tree,
335 version: clock::Global,
336}
337
338#[derive(Clone)]
339struct AutoindentRequest {
340 before_edit: BufferSnapshot,
341 edited: Vec<Anchor>,
342 inserted: Option<Vec<Range<Anchor>>>,
343}
344
345#[derive(Debug)]
346struct IndentSuggestion {
347 basis_row: u32,
348 indent: bool,
349}
350
351struct TextProvider<'a>(&'a Rope);
352
353struct BufferChunkHighlights<'a> {
354 captures: tree_sitter::QueryCaptures<'a, 'a, TextProvider<'a>>,
355 next_capture: Option<(tree_sitter::QueryMatch<'a, 'a>, usize)>,
356 stack: Vec<(usize, HighlightId)>,
357 highlight_map: HighlightMap,
358 theme: &'a SyntaxTheme,
359 _query_cursor: QueryCursorHandle,
360}
361
362pub struct BufferChunks<'a> {
363 range: Range<usize>,
364 chunks: rope::Chunks<'a>,
365 diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
366 error_depth: usize,
367 warning_depth: usize,
368 information_depth: usize,
369 hint_depth: usize,
370 highlights: Option<BufferChunkHighlights<'a>>,
371}
372
373#[derive(Clone, Copy, Debug, Default)]
374pub struct Chunk<'a> {
375 pub text: &'a str,
376 pub highlight_style: Option<HighlightStyle>,
377 pub diagnostic: Option<DiagnosticSeverity>,
378}
379
380pub(crate) struct Diff {
381 base_version: clock::Global,
382 new_text: Arc<str>,
383 changes: Vec<(ChangeTag, usize)>,
384}
385
386#[derive(Clone, Copy)]
387struct DiagnosticEndpoint {
388 offset: usize,
389 is_start: bool,
390 severity: DiagnosticSeverity,
391}
392
393impl Buffer {
394 pub fn new<T: Into<Arc<str>>>(
395 replica_id: ReplicaId,
396 base_text: T,
397 cx: &mut ModelContext<Self>,
398 ) -> Self {
399 Self::build(
400 TextBuffer::new(
401 replica_id,
402 cx.model_id() as u64,
403 History::new(base_text.into()),
404 ),
405 None,
406 )
407 }
408
409 pub fn from_file<T: Into<Arc<str>>>(
410 replica_id: ReplicaId,
411 base_text: T,
412 file: Box<dyn File>,
413 cx: &mut ModelContext<Self>,
414 ) -> Self {
415 Self::build(
416 TextBuffer::new(
417 replica_id,
418 cx.model_id() as u64,
419 History::new(base_text.into()),
420 ),
421 Some(file),
422 )
423 }
424
425 pub fn from_proto(
426 replica_id: ReplicaId,
427 message: proto::BufferState,
428 file: Option<Box<dyn File>>,
429 cx: &mut ModelContext<Self>,
430 ) -> Result<Self> {
431 let fragments_len = message.fragments.len();
432 let buffer = TextBuffer::from_parts(
433 replica_id,
434 message.id,
435 &message.visible_text,
436 &message.deleted_text,
437 message
438 .undo_map
439 .into_iter()
440 .map(proto::deserialize_undo_map_entry),
441 message
442 .fragments
443 .into_iter()
444 .enumerate()
445 .map(|(i, fragment)| {
446 proto::deserialize_buffer_fragment(fragment, i, fragments_len)
447 }),
448 message.lamport_timestamp,
449 From::from(message.version),
450 );
451 let mut this = Self::build(buffer, file);
452 for selection_set in message.selections {
453 this.remote_selections.insert(
454 selection_set.replica_id as ReplicaId,
455 SelectionSet {
456 selections: proto::deserialize_selections(selection_set.selections),
457 lamport_timestamp: clock::Lamport {
458 replica_id: selection_set.replica_id as ReplicaId,
459 value: selection_set.lamport_timestamp,
460 },
461 },
462 );
463 }
464 let snapshot = this.snapshot();
465 let entries = proto::deserialize_diagnostics(message.diagnostics);
466 this.apply_diagnostic_update(
467 DiagnosticSet::from_sorted_entries(entries.into_iter().cloned(), &snapshot),
468 cx,
469 );
470
471 this.completion_triggers = message.completion_triggers;
472
473 let deferred_ops = message
474 .deferred_operations
475 .into_iter()
476 .map(proto::deserialize_operation)
477 .collect::<Result<Vec<_>>>()?;
478 this.apply_ops(deferred_ops, cx)?;
479
480 Ok(this)
481 }
482
483 pub fn to_proto(&self) -> proto::BufferState {
484 proto::BufferState {
485 id: self.remote_id(),
486 file: self.file.as_ref().map(|f| f.to_proto()),
487 visible_text: self.text.text(),
488 deleted_text: self.text.deleted_text(),
489 undo_map: self
490 .text
491 .undo_history()
492 .map(proto::serialize_undo_map_entry)
493 .collect(),
494 version: From::from(&self.version),
495 lamport_timestamp: self.lamport_clock.value,
496 fragments: self
497 .text
498 .fragments()
499 .map(proto::serialize_buffer_fragment)
500 .collect(),
501 selections: self
502 .remote_selections
503 .iter()
504 .map(|(replica_id, set)| proto::SelectionSet {
505 replica_id: *replica_id as u32,
506 selections: proto::serialize_selections(&set.selections),
507 lamport_timestamp: set.lamport_timestamp.value,
508 })
509 .collect(),
510 diagnostics: proto::serialize_diagnostics(self.diagnostics.iter()),
511 deferred_operations: self
512 .deferred_ops
513 .iter()
514 .map(proto::serialize_operation)
515 .chain(
516 self.text
517 .deferred_ops()
518 .map(|op| proto::serialize_operation(&Operation::Buffer(op.clone()))),
519 )
520 .collect(),
521 completion_triggers: self.completion_triggers.clone(),
522 }
523 }
524
525 pub fn with_language(mut self, language: Arc<Language>, cx: &mut ModelContext<Self>) -> Self {
526 self.set_language(Some(language), cx);
527 self
528 }
529
530 pub fn with_language_server(
531 mut self,
532 server: Arc<LanguageServer>,
533 cx: &mut ModelContext<Self>,
534 ) -> Self {
535 self.set_language_server(Some(server), cx);
536 self
537 }
538
539 fn build(buffer: TextBuffer, file: Option<Box<dyn File>>) -> Self {
540 let saved_mtime;
541 if let Some(file) = file.as_ref() {
542 saved_mtime = file.mtime();
543 } else {
544 saved_mtime = UNIX_EPOCH;
545 }
546
547 Self {
548 saved_mtime,
549 saved_version: buffer.version(),
550 text: buffer,
551 file,
552 syntax_tree: Mutex::new(None),
553 parsing_in_background: false,
554 parse_count: 0,
555 sync_parse_timeout: Duration::from_millis(1),
556 autoindent_requests: Default::default(),
557 pending_autoindent: Default::default(),
558 language: None,
559 remote_selections: Default::default(),
560 selections_update_count: 0,
561 diagnostics: Default::default(),
562 diagnostics_update_count: 0,
563 language_server: None,
564 completion_triggers: Default::default(),
565 deferred_ops: OperationQueue::new(),
566 #[cfg(test)]
567 operations: Default::default(),
568 }
569 }
570
571 pub fn snapshot(&self) -> BufferSnapshot {
572 BufferSnapshot {
573 text: self.text.snapshot(),
574 tree: self.syntax_tree(),
575 remote_selections: self.remote_selections.clone(),
576 diagnostics: self.diagnostics.clone(),
577 diagnostics_update_count: self.diagnostics_update_count,
578 is_parsing: self.parsing_in_background,
579 language: self.language.clone(),
580 parse_count: self.parse_count,
581 selections_update_count: self.selections_update_count,
582 }
583 }
584
585 pub fn file(&self) -> Option<&dyn File> {
586 self.file.as_deref()
587 }
588
589 pub fn format(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
590 let file = if let Some(file) = self.file.as_ref() {
591 file
592 } else {
593 return Task::ready(Err(anyhow!("buffer has no file")));
594 };
595
596 if let Some(LanguageServerState { server, .. }) = self.language_server.as_ref() {
597 let server = server.clone();
598 let abs_path = file.as_local().unwrap().abs_path(cx);
599 let version = self.version();
600 cx.spawn(|this, mut cx| async move {
601 let edits = server
602 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
603 text_document: lsp::TextDocumentIdentifier::new(
604 lsp::Url::from_file_path(&abs_path).unwrap(),
605 ),
606 options: Default::default(),
607 work_done_progress_params: Default::default(),
608 })
609 .await?;
610
611 if let Some(edits) = edits {
612 this.update(&mut cx, |this, cx| {
613 if this.version == version {
614 this.apply_lsp_edits(edits, cx)?;
615 Ok(())
616 } else {
617 Err(anyhow!("buffer edited since starting to format"))
618 }
619 })
620 } else {
621 Ok(())
622 }
623 })
624 } else {
625 let format = file.format_remote(self.remote_id(), cx.as_mut());
626 cx.spawn(|_, _| async move {
627 if let Some(format) = format {
628 format.await?;
629 }
630 Ok(())
631 })
632 }
633 }
634
635 pub fn save(
636 &mut self,
637 cx: &mut ModelContext<Self>,
638 ) -> Task<Result<(clock::Global, SystemTime)>> {
639 let file = if let Some(file) = self.file.as_ref() {
640 file
641 } else {
642 return Task::ready(Err(anyhow!("buffer has no file")));
643 };
644 let text = self.as_rope().clone();
645 let version = self.version();
646 let save = file.save(self.remote_id(), text, version, cx.as_mut());
647 cx.spawn(|this, mut cx| async move {
648 let (version, mtime) = save.await?;
649 this.update(&mut cx, |this, cx| {
650 this.did_save(version.clone(), mtime, None, cx);
651 });
652 Ok((version, mtime))
653 })
654 }
655
656 pub fn set_language(&mut self, language: Option<Arc<Language>>, cx: &mut ModelContext<Self>) {
657 self.language = language;
658 self.reparse(cx);
659 }
660
661 pub fn set_language_server(
662 &mut self,
663 language_server: Option<Arc<lsp::LanguageServer>>,
664 cx: &mut ModelContext<Self>,
665 ) {
666 self.language_server = if let Some(server) = language_server {
667 let (latest_snapshot_tx, mut latest_snapshot_rx) =
668 watch::channel::<Option<LanguageServerSnapshot>>();
669
670 let maintain_changes = cx.background().spawn({
671 let server = server.clone();
672 async move {
673 let mut prev_snapshot: Option<LanguageServerSnapshot> = None;
674 while let Some(snapshot) = latest_snapshot_rx.recv().await {
675 if let Some(snapshot) = snapshot {
676 let uri = lsp::Url::from_file_path(&snapshot.path).unwrap();
677 if let Some(prev_snapshot) = prev_snapshot {
678 let changes = lsp::DidChangeTextDocumentParams {
679 text_document: lsp::VersionedTextDocumentIdentifier::new(
680 uri,
681 snapshot.version as i32,
682 ),
683 content_changes: snapshot
684 .buffer_snapshot
685 .edits_since::<(PointUtf16, usize)>(
686 prev_snapshot.buffer_snapshot.version(),
687 )
688 .map(|edit| {
689 let edit_start = edit.new.start.0;
690 let edit_end =
691 edit_start + (edit.old.end.0 - edit.old.start.0);
692 let new_text = snapshot
693 .buffer_snapshot
694 .text_for_range(edit.new.start.1..edit.new.end.1)
695 .collect();
696 lsp::TextDocumentContentChangeEvent {
697 range: Some(lsp::Range::new(
698 edit_start.to_lsp_position(),
699 edit_end.to_lsp_position(),
700 )),
701 range_length: None,
702 text: new_text,
703 }
704 })
705 .collect(),
706 };
707 server
708 .notify::<lsp::notification::DidChangeTextDocument>(changes)
709 .await?;
710 } else {
711 server
712 .notify::<lsp::notification::DidOpenTextDocument>(
713 lsp::DidOpenTextDocumentParams {
714 text_document: lsp::TextDocumentItem::new(
715 uri,
716 Default::default(),
717 snapshot.version as i32,
718 snapshot.buffer_snapshot.text().to_string(),
719 ),
720 },
721 )
722 .await?;
723 }
724
725 prev_snapshot = Some(snapshot);
726 }
727 }
728 Ok(())
729 }
730 });
731
732 Some(LanguageServerState {
733 latest_snapshot: latest_snapshot_tx,
734 pending_snapshots: Default::default(),
735 next_version: 0,
736 server: server.clone(),
737 _maintain_server: cx.spawn_weak(|this, mut cx| async move {
738 let mut capabilities = server.capabilities();
739 loop {
740 if let Some(capabilities) = capabilities.recv().await.flatten() {
741 if let Some(this) = this.upgrade(&cx) {
742 let triggers = capabilities
743 .completion_provider
744 .and_then(|c| c.trigger_characters)
745 .unwrap_or_default();
746 this.update(&mut cx, |this, cx| {
747 this.completion_triggers = triggers.clone();
748 this.send_operation(
749 Operation::UpdateCompletionTriggers { triggers },
750 cx,
751 );
752 });
753 } else {
754 return;
755 }
756
757 break;
758 }
759 }
760
761 maintain_changes.log_err().await;
762 }),
763 })
764 } else {
765 None
766 };
767
768 self.update_language_server(cx);
769 }
770
771 pub fn did_save(
772 &mut self,
773 version: clock::Global,
774 mtime: SystemTime,
775 new_file: Option<Box<dyn File>>,
776 cx: &mut ModelContext<Self>,
777 ) {
778 self.saved_mtime = mtime;
779 self.saved_version = version;
780 if let Some(new_file) = new_file {
781 self.file = Some(new_file);
782 }
783 if let Some((state, local_file)) = &self
784 .language_server
785 .as_ref()
786 .zip(self.file.as_ref().and_then(|f| f.as_local()))
787 {
788 cx.background()
789 .spawn(
790 state
791 .server
792 .notify::<lsp::notification::DidSaveTextDocument>(
793 lsp::DidSaveTextDocumentParams {
794 text_document: lsp::TextDocumentIdentifier {
795 uri: lsp::Url::from_file_path(local_file.abs_path(cx)).unwrap(),
796 },
797 text: None,
798 },
799 ),
800 )
801 .detach()
802 }
803 cx.emit(Event::Saved);
804 }
805
806 pub fn did_reload(
807 &mut self,
808 version: clock::Global,
809 mtime: SystemTime,
810 cx: &mut ModelContext<Self>,
811 ) {
812 self.saved_mtime = mtime;
813 self.saved_version = version;
814 if let Some(file) = self.file.as_ref().and_then(|f| f.as_local()) {
815 file.buffer_reloaded(self.remote_id(), &self.saved_version, self.saved_mtime, cx);
816 }
817 cx.emit(Event::Reloaded);
818 cx.notify();
819 }
820
821 pub fn file_updated(
822 &mut self,
823 new_file: Box<dyn File>,
824 cx: &mut ModelContext<Self>,
825 ) -> Task<()> {
826 let old_file = if let Some(file) = self.file.as_ref() {
827 file
828 } else {
829 return Task::ready(());
830 };
831 let mut file_changed = false;
832 let mut task = Task::ready(());
833
834 if new_file.path() != old_file.path() {
835 file_changed = true;
836 }
837
838 if new_file.is_deleted() {
839 if !old_file.is_deleted() {
840 file_changed = true;
841 if !self.is_dirty() {
842 cx.emit(Event::Dirtied);
843 }
844 }
845 } else {
846 let new_mtime = new_file.mtime();
847 if new_mtime != old_file.mtime() {
848 file_changed = true;
849
850 if !self.is_dirty() {
851 task = cx.spawn(|this, mut cx| {
852 async move {
853 let new_text = this.read_with(&cx, |this, cx| {
854 this.file
855 .as_ref()
856 .and_then(|file| file.as_local().map(|f| f.load(cx)))
857 });
858 if let Some(new_text) = new_text {
859 let new_text = new_text.await?;
860 let diff = this
861 .read_with(&cx, |this, cx| this.diff(new_text.into(), cx))
862 .await;
863 this.update(&mut cx, |this, cx| {
864 if this.apply_diff(diff, cx) {
865 this.did_reload(this.version(), new_mtime, cx);
866 }
867 });
868 }
869 Ok(())
870 }
871 .log_err()
872 .map(drop)
873 });
874 }
875 }
876 }
877
878 if file_changed {
879 cx.emit(Event::FileHandleChanged);
880 }
881 self.file = Some(new_file);
882 task
883 }
884
885 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
886 cx.emit(Event::Closed);
887 }
888
889 pub fn language(&self) -> Option<&Arc<Language>> {
890 self.language.as_ref()
891 }
892
893 pub fn language_server(&self) -> Option<&Arc<LanguageServer>> {
894 self.language_server.as_ref().map(|state| &state.server)
895 }
896
897 pub fn parse_count(&self) -> usize {
898 self.parse_count
899 }
900
901 pub fn selections_update_count(&self) -> usize {
902 self.selections_update_count
903 }
904
905 pub fn diagnostics_update_count(&self) -> usize {
906 self.diagnostics_update_count
907 }
908
909 pub(crate) fn syntax_tree(&self) -> Option<Tree> {
910 if let Some(syntax_tree) = self.syntax_tree.lock().as_mut() {
911 self.interpolate_tree(syntax_tree);
912 Some(syntax_tree.tree.clone())
913 } else {
914 None
915 }
916 }
917
918 #[cfg(any(test, feature = "test-support"))]
919 pub fn is_parsing(&self) -> bool {
920 self.parsing_in_background
921 }
922
923 #[cfg(test)]
924 pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
925 self.sync_parse_timeout = timeout;
926 }
927
928 fn reparse(&mut self, cx: &mut ModelContext<Self>) -> bool {
929 if self.parsing_in_background {
930 return false;
931 }
932
933 if let Some(grammar) = self.grammar().cloned() {
934 let old_tree = self.syntax_tree();
935 let text = self.as_rope().clone();
936 let parsed_version = self.version();
937 let parse_task = cx.background().spawn({
938 let grammar = grammar.clone();
939 async move { Self::parse_text(&text, old_tree, &grammar) }
940 });
941
942 match cx
943 .background()
944 .block_with_timeout(self.sync_parse_timeout, parse_task)
945 {
946 Ok(new_tree) => {
947 self.did_finish_parsing(new_tree, parsed_version, cx);
948 return true;
949 }
950 Err(parse_task) => {
951 self.parsing_in_background = true;
952 cx.spawn(move |this, mut cx| async move {
953 let new_tree = parse_task.await;
954 this.update(&mut cx, move |this, cx| {
955 let grammar_changed = this
956 .grammar()
957 .map_or(true, |curr_grammar| !Arc::ptr_eq(&grammar, curr_grammar));
958 let parse_again =
959 this.version.changed_since(&parsed_version) || grammar_changed;
960 this.parsing_in_background = false;
961 this.did_finish_parsing(new_tree, parsed_version, cx);
962
963 if parse_again && this.reparse(cx) {
964 return;
965 }
966 });
967 })
968 .detach();
969 }
970 }
971 }
972 false
973 }
974
975 fn parse_text(text: &Rope, old_tree: Option<Tree>, grammar: &Grammar) -> Tree {
976 PARSER.with(|parser| {
977 let mut parser = parser.borrow_mut();
978 parser
979 .set_language(grammar.ts_language)
980 .expect("incompatible grammar");
981 let mut chunks = text.chunks_in_range(0..text.len());
982 let tree = parser
983 .parse_with(
984 &mut move |offset, _| {
985 chunks.seek(offset);
986 chunks.next().unwrap_or("").as_bytes()
987 },
988 old_tree.as_ref(),
989 )
990 .unwrap();
991 tree
992 })
993 }
994
995 fn interpolate_tree(&self, tree: &mut SyntaxTree) {
996 for edit in self.edits_since::<(usize, Point)>(&tree.version) {
997 let (bytes, lines) = edit.flatten();
998 tree.tree.edit(&InputEdit {
999 start_byte: bytes.new.start,
1000 old_end_byte: bytes.new.start + bytes.old.len(),
1001 new_end_byte: bytes.new.end,
1002 start_position: lines.new.start.to_ts_point(),
1003 old_end_position: (lines.new.start + (lines.old.end - lines.old.start))
1004 .to_ts_point(),
1005 new_end_position: lines.new.end.to_ts_point(),
1006 });
1007 }
1008 tree.version = self.version();
1009 }
1010
1011 fn did_finish_parsing(
1012 &mut self,
1013 tree: Tree,
1014 version: clock::Global,
1015 cx: &mut ModelContext<Self>,
1016 ) {
1017 self.parse_count += 1;
1018 *self.syntax_tree.lock() = Some(SyntaxTree { tree, version });
1019 self.request_autoindent(cx);
1020 cx.emit(Event::Reparsed);
1021 cx.notify();
1022 }
1023
1024 pub fn update_diagnostics<T>(
1025 &mut self,
1026 version: Option<i32>,
1027 mut diagnostics: Vec<DiagnosticEntry<T>>,
1028 cx: &mut ModelContext<Self>,
1029 ) -> Result<()>
1030 where
1031 T: Copy + Ord + TextDimension + Sub<Output = T> + Clip + ToPoint,
1032 {
1033 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
1034 Ordering::Equal
1035 .then_with(|| b.is_primary.cmp(&a.is_primary))
1036 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
1037 .then_with(|| a.severity.cmp(&b.severity))
1038 .then_with(|| a.message.cmp(&b.message))
1039 }
1040
1041 let version = version.map(|version| version as usize);
1042 let content =
1043 if let Some((version, language_server)) = version.zip(self.language_server.as_mut()) {
1044 language_server
1045 .pending_snapshots
1046 .retain(|&v, _| v >= version);
1047 let snapshot = language_server
1048 .pending_snapshots
1049 .get(&version)
1050 .ok_or_else(|| anyhow!("missing snapshot"))?;
1051 &snapshot.buffer_snapshot
1052 } else {
1053 self.deref()
1054 };
1055
1056 diagnostics.sort_unstable_by(|a, b| {
1057 Ordering::Equal
1058 .then_with(|| a.range.start.cmp(&b.range.start))
1059 .then_with(|| b.range.end.cmp(&a.range.end))
1060 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
1061 });
1062
1063 let mut sanitized_diagnostics = Vec::new();
1064 let mut edits_since_save = content.edits_since::<T>(&self.saved_version).peekable();
1065 let mut last_edit_old_end = T::default();
1066 let mut last_edit_new_end = T::default();
1067 'outer: for entry in diagnostics {
1068 let mut start = entry.range.start;
1069 let mut end = entry.range.end;
1070
1071 // Some diagnostics are based on files on disk instead of buffers'
1072 // current contents. Adjust these diagnostics' ranges to reflect
1073 // any unsaved edits.
1074 if entry.diagnostic.is_disk_based {
1075 while let Some(edit) = edits_since_save.peek() {
1076 if edit.old.end <= start {
1077 last_edit_old_end = edit.old.end;
1078 last_edit_new_end = edit.new.end;
1079 edits_since_save.next();
1080 } else if edit.old.start <= end && edit.old.end >= start {
1081 continue 'outer;
1082 } else {
1083 break;
1084 }
1085 }
1086
1087 let start_overshoot = start - last_edit_old_end;
1088 start = last_edit_new_end;
1089 start.add_assign(&start_overshoot);
1090
1091 let end_overshoot = end - last_edit_old_end;
1092 end = last_edit_new_end;
1093 end.add_assign(&end_overshoot);
1094 }
1095
1096 let range = start.clip(Bias::Left, content)..end.clip(Bias::Right, content);
1097 let mut range = range.start.to_point(content)..range.end.to_point(content);
1098 // Expand empty ranges by one character
1099 if range.start == range.end {
1100 range.end.column += 1;
1101 range.end = content.clip_point(range.end, Bias::Right);
1102 if range.start == range.end && range.end.column > 0 {
1103 range.start.column -= 1;
1104 range.start = content.clip_point(range.start, Bias::Left);
1105 }
1106 }
1107
1108 sanitized_diagnostics.push(DiagnosticEntry {
1109 range,
1110 diagnostic: entry.diagnostic,
1111 });
1112 }
1113 drop(edits_since_save);
1114
1115 let set = DiagnosticSet::new(sanitized_diagnostics, content);
1116 self.apply_diagnostic_update(set.clone(), cx);
1117
1118 let op = Operation::UpdateDiagnostics {
1119 diagnostics: set.iter().cloned().collect(),
1120 lamport_timestamp: self.text.lamport_clock.tick(),
1121 };
1122 self.send_operation(op, cx);
1123 Ok(())
1124 }
1125
1126 fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
1127 if let Some(indent_columns) = self.compute_autoindents() {
1128 let indent_columns = cx.background().spawn(indent_columns);
1129 match cx
1130 .background()
1131 .block_with_timeout(Duration::from_micros(500), indent_columns)
1132 {
1133 Ok(indent_columns) => self.apply_autoindents(indent_columns, cx),
1134 Err(indent_columns) => {
1135 self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
1136 let indent_columns = indent_columns.await;
1137 this.update(&mut cx, |this, cx| {
1138 this.apply_autoindents(indent_columns, cx);
1139 });
1140 }));
1141 }
1142 }
1143 }
1144 }
1145
1146 fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, u32>>> {
1147 let max_rows_between_yields = 100;
1148 let snapshot = self.snapshot();
1149 if snapshot.language.is_none()
1150 || snapshot.tree.is_none()
1151 || self.autoindent_requests.is_empty()
1152 {
1153 return None;
1154 }
1155
1156 let autoindent_requests = self.autoindent_requests.clone();
1157 Some(async move {
1158 let mut indent_columns = BTreeMap::new();
1159 for request in autoindent_requests {
1160 let old_to_new_rows = request
1161 .edited
1162 .iter()
1163 .map(|anchor| anchor.summary::<Point>(&request.before_edit).row)
1164 .zip(
1165 request
1166 .edited
1167 .iter()
1168 .map(|anchor| anchor.summary::<Point>(&snapshot).row),
1169 )
1170 .collect::<BTreeMap<u32, u32>>();
1171
1172 let mut old_suggestions = HashMap::<u32, u32>::default();
1173 let old_edited_ranges =
1174 contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
1175 for old_edited_range in old_edited_ranges {
1176 let suggestions = request
1177 .before_edit
1178 .suggest_autoindents(old_edited_range.clone())
1179 .into_iter()
1180 .flatten();
1181 for (old_row, suggestion) in old_edited_range.zip(suggestions) {
1182 let indentation_basis = old_to_new_rows
1183 .get(&suggestion.basis_row)
1184 .and_then(|from_row| old_suggestions.get(from_row).copied())
1185 .unwrap_or_else(|| {
1186 request
1187 .before_edit
1188 .indent_column_for_line(suggestion.basis_row)
1189 });
1190 let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
1191 old_suggestions.insert(
1192 *old_to_new_rows.get(&old_row).unwrap(),
1193 indentation_basis + delta,
1194 );
1195 }
1196 yield_now().await;
1197 }
1198
1199 // At this point, old_suggestions contains the suggested indentation for all edited lines with respect to the state of the
1200 // buffer before the edit, but keyed by the row for these lines after the edits were applied.
1201 let new_edited_row_ranges =
1202 contiguous_ranges(old_to_new_rows.values().copied(), max_rows_between_yields);
1203 for new_edited_row_range in new_edited_row_ranges {
1204 let suggestions = snapshot
1205 .suggest_autoindents(new_edited_row_range.clone())
1206 .into_iter()
1207 .flatten();
1208 for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
1209 let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
1210 let new_indentation = indent_columns
1211 .get(&suggestion.basis_row)
1212 .copied()
1213 .unwrap_or_else(|| {
1214 snapshot.indent_column_for_line(suggestion.basis_row)
1215 })
1216 + delta;
1217 if old_suggestions
1218 .get(&new_row)
1219 .map_or(true, |old_indentation| new_indentation != *old_indentation)
1220 {
1221 indent_columns.insert(new_row, new_indentation);
1222 }
1223 }
1224 yield_now().await;
1225 }
1226
1227 if let Some(inserted) = request.inserted.as_ref() {
1228 let inserted_row_ranges = contiguous_ranges(
1229 inserted
1230 .iter()
1231 .map(|range| range.to_point(&snapshot))
1232 .flat_map(|range| range.start.row..range.end.row + 1),
1233 max_rows_between_yields,
1234 );
1235 for inserted_row_range in inserted_row_ranges {
1236 let suggestions = snapshot
1237 .suggest_autoindents(inserted_row_range.clone())
1238 .into_iter()
1239 .flatten();
1240 for (row, suggestion) in inserted_row_range.zip(suggestions) {
1241 let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
1242 let new_indentation = indent_columns
1243 .get(&suggestion.basis_row)
1244 .copied()
1245 .unwrap_or_else(|| {
1246 snapshot.indent_column_for_line(suggestion.basis_row)
1247 })
1248 + delta;
1249 indent_columns.insert(row, new_indentation);
1250 }
1251 yield_now().await;
1252 }
1253 }
1254 }
1255 indent_columns
1256 })
1257 }
1258
1259 fn apply_autoindents(
1260 &mut self,
1261 indent_columns: BTreeMap<u32, u32>,
1262 cx: &mut ModelContext<Self>,
1263 ) {
1264 self.autoindent_requests.clear();
1265 self.start_transaction();
1266 for (row, indent_column) in &indent_columns {
1267 self.set_indent_column_for_line(*row, *indent_column, cx);
1268 }
1269 self.end_transaction(cx);
1270 }
1271
1272 fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
1273 let current_column = self.indent_column_for_line(row);
1274 if column > current_column {
1275 let offset = Point::new(row, 0).to_offset(&*self);
1276 self.edit(
1277 [offset..offset],
1278 " ".repeat((column - current_column) as usize),
1279 cx,
1280 );
1281 } else if column < current_column {
1282 self.edit(
1283 [Point::new(row, 0)..Point::new(row, current_column - column)],
1284 "",
1285 cx,
1286 );
1287 }
1288 }
1289
1290 pub(crate) fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
1291 // TODO: it would be nice to not allocate here.
1292 let old_text = self.text();
1293 let base_version = self.version();
1294 cx.background().spawn(async move {
1295 let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1296 .iter_all_changes()
1297 .map(|c| (c.tag(), c.value().len()))
1298 .collect::<Vec<_>>();
1299 Diff {
1300 base_version,
1301 new_text,
1302 changes,
1303 }
1304 })
1305 }
1306
1307 pub(crate) fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1308 if self.version == diff.base_version {
1309 self.start_transaction();
1310 let mut offset = 0;
1311 for (tag, len) in diff.changes {
1312 let range = offset..(offset + len);
1313 match tag {
1314 ChangeTag::Equal => offset += len,
1315 ChangeTag::Delete => {
1316 self.edit(Some(range), "", cx);
1317 }
1318 ChangeTag::Insert => {
1319 self.edit(Some(offset..offset), &diff.new_text[range], cx);
1320 offset += len;
1321 }
1322 }
1323 }
1324 self.end_transaction(cx);
1325 true
1326 } else {
1327 false
1328 }
1329 }
1330
1331 pub fn is_dirty(&self) -> bool {
1332 !self.saved_version.observed_all(&self.version)
1333 || self.file.as_ref().map_or(false, |file| file.is_deleted())
1334 }
1335
1336 pub fn has_conflict(&self) -> bool {
1337 !self.saved_version.observed_all(&self.version)
1338 && self
1339 .file
1340 .as_ref()
1341 .map_or(false, |file| file.mtime() > self.saved_mtime)
1342 }
1343
1344 pub fn subscribe(&mut self) -> Subscription {
1345 self.text.subscribe()
1346 }
1347
1348 pub fn start_transaction(&mut self) -> Option<TransactionId> {
1349 self.start_transaction_at(Instant::now())
1350 }
1351
1352 pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1353 self.text.start_transaction_at(now)
1354 }
1355
1356 pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1357 self.end_transaction_at(Instant::now(), cx)
1358 }
1359
1360 pub fn end_transaction_at(
1361 &mut self,
1362 now: Instant,
1363 cx: &mut ModelContext<Self>,
1364 ) -> Option<TransactionId> {
1365 if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1366 let was_dirty = start_version != self.saved_version;
1367 self.did_edit(&start_version, was_dirty, cx);
1368 Some(transaction_id)
1369 } else {
1370 None
1371 }
1372 }
1373
1374 pub fn avoid_grouping_next_transaction(&mut self) {
1375 self.text.avoid_grouping_next_transaction();
1376 }
1377
1378 pub fn set_active_selections(
1379 &mut self,
1380 selections: Arc<[Selection<Anchor>]>,
1381 cx: &mut ModelContext<Self>,
1382 ) {
1383 let lamport_timestamp = self.text.lamport_clock.tick();
1384 self.remote_selections.insert(
1385 self.text.replica_id(),
1386 SelectionSet {
1387 selections: selections.clone(),
1388 lamport_timestamp,
1389 },
1390 );
1391 self.send_operation(
1392 Operation::UpdateSelections {
1393 replica_id: self.text.replica_id(),
1394 selections,
1395 lamport_timestamp,
1396 },
1397 cx,
1398 );
1399 }
1400
1401 pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1402 self.set_active_selections(Arc::from([]), cx);
1403 }
1404
1405 fn update_language_server(&mut self, cx: &AppContext) {
1406 let language_server = if let Some(language_server) = self.language_server.as_mut() {
1407 language_server
1408 } else {
1409 return;
1410 };
1411 let abs_path = self
1412 .file
1413 .as_ref()
1414 .and_then(|f| f.as_local())
1415 .map_or(Path::new("/").to_path_buf(), |file| file.abs_path(cx));
1416
1417 let version = post_inc(&mut language_server.next_version);
1418 let snapshot = LanguageServerSnapshot {
1419 buffer_snapshot: self.text.snapshot(),
1420 version,
1421 path: Arc::from(abs_path),
1422 };
1423 language_server
1424 .pending_snapshots
1425 .insert(version, snapshot.clone());
1426 let _ = language_server
1427 .latest_snapshot
1428 .blocking_send(Some(snapshot));
1429 }
1430
1431 pub fn edit<I, S, T>(
1432 &mut self,
1433 ranges_iter: I,
1434 new_text: T,
1435 cx: &mut ModelContext<Self>,
1436 ) -> Option<clock::Local>
1437 where
1438 I: IntoIterator<Item = Range<S>>,
1439 S: ToOffset,
1440 T: Into<String>,
1441 {
1442 self.edit_internal(ranges_iter, new_text, false, cx)
1443 }
1444
1445 pub fn edit_with_autoindent<I, S, T>(
1446 &mut self,
1447 ranges_iter: I,
1448 new_text: T,
1449 cx: &mut ModelContext<Self>,
1450 ) -> Option<clock::Local>
1451 where
1452 I: IntoIterator<Item = Range<S>>,
1453 S: ToOffset,
1454 T: Into<String>,
1455 {
1456 self.edit_internal(ranges_iter, new_text, true, cx)
1457 }
1458
1459 pub fn edit_internal<I, S, T>(
1460 &mut self,
1461 ranges_iter: I,
1462 new_text: T,
1463 autoindent: bool,
1464 cx: &mut ModelContext<Self>,
1465 ) -> Option<clock::Local>
1466 where
1467 I: IntoIterator<Item = Range<S>>,
1468 S: ToOffset,
1469 T: Into<String>,
1470 {
1471 let new_text = new_text.into();
1472
1473 // Skip invalid ranges and coalesce contiguous ones.
1474 let mut ranges: Vec<Range<usize>> = Vec::new();
1475 for range in ranges_iter {
1476 let range = range.start.to_offset(self)..range.end.to_offset(self);
1477 if !new_text.is_empty() || !range.is_empty() {
1478 if let Some(prev_range) = ranges.last_mut() {
1479 if prev_range.end >= range.start {
1480 prev_range.end = cmp::max(prev_range.end, range.end);
1481 } else {
1482 ranges.push(range);
1483 }
1484 } else {
1485 ranges.push(range);
1486 }
1487 }
1488 }
1489 if ranges.is_empty() {
1490 return None;
1491 }
1492
1493 self.start_transaction();
1494 self.pending_autoindent.take();
1495 let autoindent_request = if autoindent && self.language.is_some() {
1496 let before_edit = self.snapshot();
1497 let edited = ranges
1498 .iter()
1499 .filter_map(|range| {
1500 let start = range.start.to_point(self);
1501 if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1502 None
1503 } else {
1504 Some(self.anchor_before(range.start))
1505 }
1506 })
1507 .collect();
1508 Some((before_edit, edited))
1509 } else {
1510 None
1511 };
1512
1513 let first_newline_ix = new_text.find('\n');
1514 let new_text_len = new_text.len();
1515
1516 let edit = self.text.edit(ranges.iter().cloned(), new_text);
1517 let edit_id = edit.timestamp.local();
1518
1519 if let Some((before_edit, edited)) = autoindent_request {
1520 let mut inserted = None;
1521 if let Some(first_newline_ix) = first_newline_ix {
1522 let mut delta = 0isize;
1523 inserted = Some(
1524 ranges
1525 .iter()
1526 .map(|range| {
1527 let start =
1528 (delta + range.start as isize) as usize + first_newline_ix + 1;
1529 let end = (delta + range.start as isize) as usize + new_text_len;
1530 delta +=
1531 (range.end as isize - range.start as isize) + new_text_len as isize;
1532 self.anchor_before(start)..self.anchor_after(end)
1533 })
1534 .collect(),
1535 );
1536 }
1537
1538 self.autoindent_requests.push(Arc::new(AutoindentRequest {
1539 before_edit,
1540 edited,
1541 inserted,
1542 }));
1543 }
1544
1545 self.end_transaction(cx);
1546 self.send_operation(Operation::Buffer(text::Operation::Edit(edit)), cx);
1547 Some(edit_id)
1548 }
1549
1550 fn apply_lsp_edits(
1551 &mut self,
1552 edits: Vec<lsp::TextEdit>,
1553 cx: &mut ModelContext<Self>,
1554 ) -> Result<Vec<clock::Local>> {
1555 for edit in &edits {
1556 let range = range_from_lsp(edit.range);
1557 if self.clip_point_utf16(range.start, Bias::Left) != range.start
1558 || self.clip_point_utf16(range.end, Bias::Left) != range.end
1559 {
1560 return Err(anyhow!(
1561 "invalid formatting edits received from language server"
1562 ));
1563 }
1564 }
1565
1566 self.start_transaction();
1567 let edit_ids = edits
1568 .into_iter()
1569 .rev()
1570 .filter_map(|edit| self.edit([range_from_lsp(edit.range)], edit.new_text, cx))
1571 .collect();
1572 self.end_transaction(cx);
1573 Ok(edit_ids)
1574 }
1575
1576 fn did_edit(
1577 &mut self,
1578 old_version: &clock::Global,
1579 was_dirty: bool,
1580 cx: &mut ModelContext<Self>,
1581 ) {
1582 if self.edits_since::<usize>(old_version).next().is_none() {
1583 return;
1584 }
1585
1586 self.reparse(cx);
1587 self.update_language_server(cx);
1588
1589 cx.emit(Event::Edited);
1590 if !was_dirty {
1591 cx.emit(Event::Dirtied);
1592 }
1593 cx.notify();
1594 }
1595
1596 fn grammar(&self) -> Option<&Arc<Grammar>> {
1597 self.language.as_ref().and_then(|l| l.grammar.as_ref())
1598 }
1599
1600 pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1601 &mut self,
1602 ops: I,
1603 cx: &mut ModelContext<Self>,
1604 ) -> Result<()> {
1605 self.pending_autoindent.take();
1606 let was_dirty = self.is_dirty();
1607 let old_version = self.version.clone();
1608 let mut deferred_ops = Vec::new();
1609 let buffer_ops = ops
1610 .into_iter()
1611 .filter_map(|op| match op {
1612 Operation::Buffer(op) => Some(op),
1613 _ => {
1614 if self.can_apply_op(&op) {
1615 self.apply_op(op, cx);
1616 } else {
1617 deferred_ops.push(op);
1618 }
1619 None
1620 }
1621 })
1622 .collect::<Vec<_>>();
1623 self.text.apply_ops(buffer_ops)?;
1624 self.deferred_ops.insert(deferred_ops);
1625 self.flush_deferred_ops(cx);
1626 self.did_edit(&old_version, was_dirty, cx);
1627 // Notify independently of whether the buffer was edited as the operations could include a
1628 // selection update.
1629 cx.notify();
1630 Ok(())
1631 }
1632
1633 fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1634 let mut deferred_ops = Vec::new();
1635 for op in self.deferred_ops.drain().iter().cloned() {
1636 if self.can_apply_op(&op) {
1637 self.apply_op(op, cx);
1638 } else {
1639 deferred_ops.push(op);
1640 }
1641 }
1642 self.deferred_ops.insert(deferred_ops);
1643 }
1644
1645 fn can_apply_op(&self, operation: &Operation) -> bool {
1646 match operation {
1647 Operation::Buffer(_) => {
1648 unreachable!("buffer operations should never be applied at this layer")
1649 }
1650 Operation::UpdateDiagnostics {
1651 diagnostics: diagnostic_set,
1652 ..
1653 } => diagnostic_set.iter().all(|diagnostic| {
1654 self.text.can_resolve(&diagnostic.range.start)
1655 && self.text.can_resolve(&diagnostic.range.end)
1656 }),
1657 Operation::UpdateSelections { selections, .. } => selections
1658 .iter()
1659 .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1660 Operation::UpdateCompletionTriggers { .. } => true,
1661 }
1662 }
1663
1664 fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1665 match operation {
1666 Operation::Buffer(_) => {
1667 unreachable!("buffer operations should never be applied at this layer")
1668 }
1669 Operation::UpdateDiagnostics {
1670 diagnostics: diagnostic_set,
1671 ..
1672 } => {
1673 let snapshot = self.snapshot();
1674 self.apply_diagnostic_update(
1675 DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1676 cx,
1677 );
1678 }
1679 Operation::UpdateSelections {
1680 replica_id,
1681 selections,
1682 lamport_timestamp,
1683 } => {
1684 if let Some(set) = self.remote_selections.get(&replica_id) {
1685 if set.lamport_timestamp > lamport_timestamp {
1686 return;
1687 }
1688 }
1689
1690 self.remote_selections.insert(
1691 replica_id,
1692 SelectionSet {
1693 selections,
1694 lamport_timestamp,
1695 },
1696 );
1697 self.text.lamport_clock.observe(lamport_timestamp);
1698 self.selections_update_count += 1;
1699 }
1700 Operation::UpdateCompletionTriggers { triggers } => {
1701 self.completion_triggers = triggers;
1702 }
1703 }
1704 }
1705
1706 fn apply_diagnostic_update(&mut self, diagnostics: DiagnosticSet, cx: &mut ModelContext<Self>) {
1707 self.diagnostics = diagnostics;
1708 self.diagnostics_update_count += 1;
1709 cx.notify();
1710 cx.emit(Event::DiagnosticsUpdated);
1711 }
1712
1713 #[cfg(not(test))]
1714 pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1715 if let Some(file) = &self.file {
1716 file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1717 }
1718 }
1719
1720 #[cfg(test)]
1721 pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1722 self.operations.push(operation);
1723 }
1724
1725 pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1726 self.remote_selections.remove(&replica_id);
1727 cx.notify();
1728 }
1729
1730 pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1731 let was_dirty = self.is_dirty();
1732 let old_version = self.version.clone();
1733
1734 if let Some((transaction_id, operation)) = self.text.undo() {
1735 self.send_operation(Operation::Buffer(operation), cx);
1736 self.did_edit(&old_version, was_dirty, cx);
1737 Some(transaction_id)
1738 } else {
1739 None
1740 }
1741 }
1742
1743 pub fn undo_transaction(
1744 &mut self,
1745 transaction_id: TransactionId,
1746 cx: &mut ModelContext<Self>,
1747 ) -> bool {
1748 let was_dirty = self.is_dirty();
1749 let old_version = self.version.clone();
1750
1751 if let Some(operation) = self.text.undo_transaction(transaction_id) {
1752 self.send_operation(Operation::Buffer(operation), cx);
1753 self.did_edit(&old_version, was_dirty, cx);
1754 true
1755 } else {
1756 false
1757 }
1758 }
1759
1760 pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1761 let was_dirty = self.is_dirty();
1762 let old_version = self.version.clone();
1763
1764 if let Some((transaction_id, operation)) = self.text.redo() {
1765 self.send_operation(Operation::Buffer(operation), cx);
1766 self.did_edit(&old_version, was_dirty, cx);
1767 Some(transaction_id)
1768 } else {
1769 None
1770 }
1771 }
1772
1773 pub fn redo_transaction(
1774 &mut self,
1775 transaction_id: TransactionId,
1776 cx: &mut ModelContext<Self>,
1777 ) -> bool {
1778 let was_dirty = self.is_dirty();
1779 let old_version = self.version.clone();
1780
1781 if let Some(operation) = self.text.redo_transaction(transaction_id) {
1782 self.send_operation(Operation::Buffer(operation), cx);
1783 self.did_edit(&old_version, was_dirty, cx);
1784 true
1785 } else {
1786 false
1787 }
1788 }
1789
1790 pub fn completions<T>(
1791 &self,
1792 position: T,
1793 cx: &mut ModelContext<Self>,
1794 ) -> Task<Result<Vec<Completion<Anchor>>>>
1795 where
1796 T: ToOffset,
1797 {
1798 let file = if let Some(file) = self.file.as_ref() {
1799 file
1800 } else {
1801 return Task::ready(Ok(Default::default()));
1802 };
1803
1804 if let Some(file) = file.as_local() {
1805 let server = if let Some(lang) = self.language_server.as_ref() {
1806 lang.server.clone()
1807 } else {
1808 return Task::ready(Ok(Default::default()));
1809 };
1810 let abs_path = file.abs_path(cx);
1811 let position = self.offset_to_point_utf16(position.to_offset(self));
1812
1813 cx.spawn(|this, cx| async move {
1814 let completions = server
1815 .request::<lsp::request::Completion>(lsp::CompletionParams {
1816 text_document_position: lsp::TextDocumentPositionParams::new(
1817 lsp::TextDocumentIdentifier::new(
1818 lsp::Url::from_file_path(abs_path).unwrap(),
1819 ),
1820 position.to_lsp_position(),
1821 ),
1822 context: Default::default(),
1823 work_done_progress_params: Default::default(),
1824 partial_result_params: Default::default(),
1825 })
1826 .await?;
1827
1828 let completions = if let Some(completions) = completions {
1829 match completions {
1830 lsp::CompletionResponse::Array(completions) => completions,
1831 lsp::CompletionResponse::List(list) => list.items,
1832 }
1833 } else {
1834 Default::default()
1835 };
1836
1837 this.read_with(&cx, |this, _| {
1838 Ok(completions.into_iter().filter_map(|lsp_completion| {
1839 let (old_range, new_text) = match lsp_completion.text_edit.as_ref()? {
1840 lsp::CompletionTextEdit::Edit(edit) => (range_from_lsp(edit.range), edit.new_text.clone()),
1841 lsp::CompletionTextEdit::InsertAndReplace(_) => {
1842 log::info!("received an insert and replace completion but we don't yet support that");
1843 return None
1844 },
1845 };
1846
1847 let clipped_start = this.clip_point_utf16(old_range.start, Bias::Left);
1848 let clipped_end = this.clip_point_utf16(old_range.end, Bias::Left) ;
1849 if clipped_start == old_range.start && clipped_end == old_range.end {
1850 Some(Completion {
1851 old_range: this.anchor_before(old_range.start)..this.anchor_after(old_range.end),
1852 new_text,
1853 lsp_completion,
1854 })
1855 } else {
1856 None
1857 }
1858 }).collect())
1859 })
1860 })
1861 } else {
1862 file.completions(self.remote_id(), self.anchor_before(position), cx.as_mut())
1863 }
1864 }
1865
1866 pub fn apply_additional_edits_for_completion(
1867 &mut self,
1868 completion: Completion<Anchor>,
1869 push_to_history: bool,
1870 cx: &mut ModelContext<Self>,
1871 ) -> Task<Result<Vec<clock::Local>>> {
1872 let file = if let Some(file) = self.file.as_ref() {
1873 file
1874 } else {
1875 return Task::ready(Ok(Default::default()));
1876 };
1877
1878 if file.is_local() {
1879 let server = if let Some(lang) = self.language_server.as_ref() {
1880 lang.server.clone()
1881 } else {
1882 return Task::ready(Ok(Default::default()));
1883 };
1884
1885 cx.spawn(|this, mut cx| async move {
1886 let resolved_completion = server
1887 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
1888 .await?;
1889 if let Some(additional_edits) = resolved_completion.additional_text_edits {
1890 this.update(&mut cx, |this, cx| {
1891 this.avoid_grouping_next_transaction();
1892 this.start_transaction();
1893 let edit_ids = this.apply_lsp_edits(additional_edits, cx);
1894 if let Some(transaction_id) = this.end_transaction(cx) {
1895 if !push_to_history {
1896 this.text.forget_transaction(transaction_id);
1897 }
1898 }
1899 edit_ids
1900 })
1901 } else {
1902 Ok(Default::default())
1903 }
1904 })
1905 } else {
1906 let apply_edits = file.apply_additional_edits_for_completion(
1907 self.remote_id(),
1908 completion,
1909 cx.as_mut(),
1910 );
1911 cx.spawn(|this, mut cx| async move {
1912 let edit_ids = apply_edits.await?;
1913 if push_to_history {
1914 this.update(&mut cx, |this, _| {
1915 this.text
1916 .push_transaction(edit_ids.iter().copied(), Instant::now());
1917 });
1918 }
1919 Ok(edit_ids)
1920 })
1921 }
1922 }
1923
1924 pub fn completion_triggers(&self) -> &[String] {
1925 &self.completion_triggers
1926 }
1927}
1928
1929#[cfg(any(test, feature = "test-support"))]
1930impl Buffer {
1931 pub fn set_group_interval(&mut self, group_interval: Duration) {
1932 self.text.set_group_interval(group_interval);
1933 }
1934
1935 pub fn randomly_edit<T>(
1936 &mut self,
1937 rng: &mut T,
1938 old_range_count: usize,
1939 cx: &mut ModelContext<Self>,
1940 ) where
1941 T: rand::Rng,
1942 {
1943 let mut old_ranges: Vec<Range<usize>> = Vec::new();
1944 for _ in 0..old_range_count {
1945 let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1946 if last_end > self.len() {
1947 break;
1948 }
1949 old_ranges.push(self.text.random_byte_range(last_end, rng));
1950 }
1951 let new_text_len = rng.gen_range(0..10);
1952 let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1953 .take(new_text_len)
1954 .collect();
1955 log::info!(
1956 "mutating buffer {} at {:?}: {:?}",
1957 self.replica_id(),
1958 old_ranges,
1959 new_text
1960 );
1961 self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1962 }
1963
1964 pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1965 let was_dirty = self.is_dirty();
1966 let old_version = self.version.clone();
1967
1968 let ops = self.text.randomly_undo_redo(rng);
1969 if !ops.is_empty() {
1970 for op in ops {
1971 self.send_operation(Operation::Buffer(op), cx);
1972 self.did_edit(&old_version, was_dirty, cx);
1973 }
1974 }
1975 }
1976}
1977
1978impl Entity for Buffer {
1979 type Event = Event;
1980
1981 fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1982 if let Some(file) = self.file.as_ref() {
1983 file.buffer_removed(self.remote_id(), cx);
1984 }
1985 }
1986}
1987
1988impl Deref for Buffer {
1989 type Target = TextBuffer;
1990
1991 fn deref(&self) -> &Self::Target {
1992 &self.text
1993 }
1994}
1995
1996impl BufferSnapshot {
1997 fn suggest_autoindents<'a>(
1998 &'a self,
1999 row_range: Range<u32>,
2000 ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
2001 let mut query_cursor = QueryCursorHandle::new();
2002 if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
2003 let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2004
2005 // Get the "indentation ranges" that intersect this row range.
2006 let indent_capture_ix = grammar.indents_query.capture_index_for_name("indent");
2007 let end_capture_ix = grammar.indents_query.capture_index_for_name("end");
2008 query_cursor.set_point_range(
2009 Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
2010 ..Point::new(row_range.end, 0).to_ts_point(),
2011 );
2012 let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
2013 for mat in query_cursor.matches(
2014 &grammar.indents_query,
2015 tree.root_node(),
2016 TextProvider(self.as_rope()),
2017 ) {
2018 let mut node_kind = "";
2019 let mut start: Option<Point> = None;
2020 let mut end: Option<Point> = None;
2021 for capture in mat.captures {
2022 if Some(capture.index) == indent_capture_ix {
2023 node_kind = capture.node.kind();
2024 start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2025 end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2026 } else if Some(capture.index) == end_capture_ix {
2027 end = Some(Point::from_ts_point(capture.node.start_position().into()));
2028 }
2029 }
2030
2031 if let Some((start, end)) = start.zip(end) {
2032 if start.row == end.row {
2033 continue;
2034 }
2035
2036 let range = start..end;
2037 match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
2038 Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
2039 Ok(ix) => {
2040 let prev_range = &mut indentation_ranges[ix];
2041 prev_range.0.end = prev_range.0.end.max(range.end);
2042 }
2043 }
2044 }
2045 }
2046
2047 let mut prev_row = prev_non_blank_row.unwrap_or(0);
2048 Some(row_range.map(move |row| {
2049 let row_start = Point::new(row, self.indent_column_for_line(row));
2050
2051 let mut indent_from_prev_row = false;
2052 let mut outdent_to_row = u32::MAX;
2053 for (range, _node_kind) in &indentation_ranges {
2054 if range.start.row >= row {
2055 break;
2056 }
2057
2058 if range.start.row == prev_row && range.end > row_start {
2059 indent_from_prev_row = true;
2060 }
2061 if range.end.row >= prev_row && range.end <= row_start {
2062 outdent_to_row = outdent_to_row.min(range.start.row);
2063 }
2064 }
2065
2066 let suggestion = if outdent_to_row == prev_row {
2067 IndentSuggestion {
2068 basis_row: prev_row,
2069 indent: false,
2070 }
2071 } else if indent_from_prev_row {
2072 IndentSuggestion {
2073 basis_row: prev_row,
2074 indent: true,
2075 }
2076 } else if outdent_to_row < prev_row {
2077 IndentSuggestion {
2078 basis_row: outdent_to_row,
2079 indent: false,
2080 }
2081 } else {
2082 IndentSuggestion {
2083 basis_row: prev_row,
2084 indent: false,
2085 }
2086 };
2087
2088 prev_row = row;
2089 suggestion
2090 }))
2091 } else {
2092 None
2093 }
2094 }
2095
2096 fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2097 while row > 0 {
2098 row -= 1;
2099 if !self.is_line_blank(row) {
2100 return Some(row);
2101 }
2102 }
2103 None
2104 }
2105
2106 pub fn chunks<'a, T: ToOffset>(
2107 &'a self,
2108 range: Range<T>,
2109 theme: Option<&'a SyntaxTheme>,
2110 ) -> BufferChunks<'a> {
2111 let range = range.start.to_offset(self)..range.end.to_offset(self);
2112
2113 let mut highlights = None;
2114 let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
2115 if let Some(theme) = theme {
2116 for entry in self.diagnostics_in_range::<_, usize>(range.clone()) {
2117 diagnostic_endpoints.push(DiagnosticEndpoint {
2118 offset: entry.range.start,
2119 is_start: true,
2120 severity: entry.diagnostic.severity,
2121 });
2122 diagnostic_endpoints.push(DiagnosticEndpoint {
2123 offset: entry.range.end,
2124 is_start: false,
2125 severity: entry.diagnostic.severity,
2126 });
2127 }
2128 diagnostic_endpoints
2129 .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
2130
2131 if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
2132 let mut query_cursor = QueryCursorHandle::new();
2133
2134 // TODO - add a Tree-sitter API to remove the need for this.
2135 let cursor = unsafe {
2136 std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
2137 };
2138 let captures = cursor.set_byte_range(range.clone()).captures(
2139 &grammar.highlights_query,
2140 tree.root_node(),
2141 TextProvider(self.text.as_rope()),
2142 );
2143 highlights = Some(BufferChunkHighlights {
2144 captures,
2145 next_capture: None,
2146 stack: Default::default(),
2147 highlight_map: grammar.highlight_map(),
2148 _query_cursor: query_cursor,
2149 theme,
2150 })
2151 }
2152 }
2153
2154 let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
2155 let chunks = self.text.as_rope().chunks_in_range(range.clone());
2156
2157 BufferChunks {
2158 range,
2159 chunks,
2160 diagnostic_endpoints,
2161 error_depth: 0,
2162 warning_depth: 0,
2163 information_depth: 0,
2164 hint_depth: 0,
2165 highlights,
2166 }
2167 }
2168
2169 pub fn language(&self) -> Option<&Arc<Language>> {
2170 self.language.as_ref()
2171 }
2172
2173 fn grammar(&self) -> Option<&Arc<Grammar>> {
2174 self.language
2175 .as_ref()
2176 .and_then(|language| language.grammar.as_ref())
2177 }
2178
2179 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2180 if let Some(tree) = self.tree.as_ref() {
2181 let root = tree.root_node();
2182 let range = range.start.to_offset(self)..range.end.to_offset(self);
2183 let mut node = root.descendant_for_byte_range(range.start, range.end);
2184 while node.map_or(false, |n| n.byte_range() == range) {
2185 node = node.unwrap().parent();
2186 }
2187 node.map(|n| n.byte_range())
2188 } else {
2189 None
2190 }
2191 }
2192
2193 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2194 let tree = self.tree.as_ref()?;
2195 let grammar = self
2196 .language
2197 .as_ref()
2198 .and_then(|language| language.grammar.as_ref())?;
2199
2200 let mut cursor = QueryCursorHandle::new();
2201 let matches = cursor.matches(
2202 &grammar.outline_query,
2203 tree.root_node(),
2204 TextProvider(self.as_rope()),
2205 );
2206
2207 let mut chunks = self.chunks(0..self.len(), theme);
2208
2209 let item_capture_ix = grammar.outline_query.capture_index_for_name("item")?;
2210 let name_capture_ix = grammar.outline_query.capture_index_for_name("name")?;
2211 let context_capture_ix = grammar
2212 .outline_query
2213 .capture_index_for_name("context")
2214 .unwrap_or(u32::MAX);
2215
2216 let mut stack = Vec::<Range<usize>>::new();
2217 let items = matches
2218 .filter_map(|mat| {
2219 let item_node = mat.nodes_for_capture_index(item_capture_ix).next()?;
2220 let range = item_node.start_byte()..item_node.end_byte();
2221 let mut text = String::new();
2222 let mut name_ranges = Vec::new();
2223 let mut highlight_ranges = Vec::new();
2224
2225 for capture in mat.captures {
2226 let node_is_name;
2227 if capture.index == name_capture_ix {
2228 node_is_name = true;
2229 } else if capture.index == context_capture_ix {
2230 node_is_name = false;
2231 } else {
2232 continue;
2233 }
2234
2235 let range = capture.node.start_byte()..capture.node.end_byte();
2236 if !text.is_empty() {
2237 text.push(' ');
2238 }
2239 if node_is_name {
2240 let mut start = text.len();
2241 let end = start + range.len();
2242
2243 // When multiple names are captured, then the matcheable text
2244 // includes the whitespace in between the names.
2245 if !name_ranges.is_empty() {
2246 start -= 1;
2247 }
2248
2249 name_ranges.push(start..end);
2250 }
2251
2252 let mut offset = range.start;
2253 chunks.seek(offset);
2254 while let Some(mut chunk) = chunks.next() {
2255 if chunk.text.len() > range.end - offset {
2256 chunk.text = &chunk.text[0..(range.end - offset)];
2257 offset = range.end;
2258 } else {
2259 offset += chunk.text.len();
2260 }
2261 if let Some(style) = chunk.highlight_style {
2262 let start = text.len();
2263 let end = start + chunk.text.len();
2264 highlight_ranges.push((start..end, style));
2265 }
2266 text.push_str(chunk.text);
2267 if offset >= range.end {
2268 break;
2269 }
2270 }
2271 }
2272
2273 while stack.last().map_or(false, |prev_range| {
2274 !prev_range.contains(&range.start) || !prev_range.contains(&range.end)
2275 }) {
2276 stack.pop();
2277 }
2278 stack.push(range.clone());
2279
2280 Some(OutlineItem {
2281 depth: stack.len() - 1,
2282 range: self.anchor_after(range.start)..self.anchor_before(range.end),
2283 text,
2284 highlight_ranges,
2285 name_ranges,
2286 })
2287 })
2288 .collect::<Vec<_>>();
2289
2290 if items.is_empty() {
2291 None
2292 } else {
2293 Some(Outline::new(items))
2294 }
2295 }
2296
2297 pub fn enclosing_bracket_ranges<T: ToOffset>(
2298 &self,
2299 range: Range<T>,
2300 ) -> Option<(Range<usize>, Range<usize>)> {
2301 let (grammar, tree) = self.grammar().zip(self.tree.as_ref())?;
2302 let open_capture_ix = grammar.brackets_query.capture_index_for_name("open")?;
2303 let close_capture_ix = grammar.brackets_query.capture_index_for_name("close")?;
2304
2305 // Find bracket pairs that *inclusively* contain the given range.
2306 let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
2307 let mut cursor = QueryCursorHandle::new();
2308 let matches = cursor.set_byte_range(range).matches(
2309 &grammar.brackets_query,
2310 tree.root_node(),
2311 TextProvider(self.as_rope()),
2312 );
2313
2314 // Get the ranges of the innermost pair of brackets.
2315 matches
2316 .filter_map(|mat| {
2317 let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
2318 let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
2319 Some((open.byte_range(), close.byte_range()))
2320 })
2321 .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
2322 }
2323
2324 /*
2325 impl BufferSnapshot
2326 pub fn remote_selections_in_range(&self, Range<Anchor>) -> impl Iterator<Item = (ReplicaId, impl Iterator<Item = &Selection<Anchor>>)>
2327 pub fn remote_selections_in_range(&self, Range<Anchor>) -> impl Iterator<Item = (ReplicaId, i
2328 */
2329
2330 pub fn remote_selections_in_range<'a>(
2331 &'a self,
2332 range: Range<Anchor>,
2333 ) -> impl 'a + Iterator<Item = (ReplicaId, impl 'a + Iterator<Item = &'a Selection<Anchor>>)>
2334 {
2335 self.remote_selections
2336 .iter()
2337 .filter(|(replica_id, set)| {
2338 **replica_id != self.text.replica_id() && !set.selections.is_empty()
2339 })
2340 .map(move |(replica_id, set)| {
2341 let start_ix = match set.selections.binary_search_by(|probe| {
2342 probe
2343 .end
2344 .cmp(&range.start, self)
2345 .unwrap()
2346 .then(Ordering::Greater)
2347 }) {
2348 Ok(ix) | Err(ix) => ix,
2349 };
2350 let end_ix = match set.selections.binary_search_by(|probe| {
2351 probe
2352 .start
2353 .cmp(&range.end, self)
2354 .unwrap()
2355 .then(Ordering::Less)
2356 }) {
2357 Ok(ix) | Err(ix) => ix,
2358 };
2359
2360 (*replica_id, set.selections[start_ix..end_ix].iter())
2361 })
2362 }
2363
2364 pub fn diagnostics_in_range<'a, T, O>(
2365 &'a self,
2366 search_range: Range<T>,
2367 ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2368 where
2369 T: 'a + Clone + ToOffset,
2370 O: 'a + FromAnchor,
2371 {
2372 self.diagnostics.range(search_range.clone(), self, true)
2373 }
2374
2375 pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
2376 let mut groups = Vec::new();
2377 self.diagnostics.groups(&mut groups, self);
2378 groups
2379 }
2380
2381 pub fn diagnostic_group<'a, O>(
2382 &'a self,
2383 group_id: usize,
2384 ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2385 where
2386 O: 'a + FromAnchor,
2387 {
2388 self.diagnostics.group(group_id, self)
2389 }
2390
2391 pub fn diagnostics_update_count(&self) -> usize {
2392 self.diagnostics_update_count
2393 }
2394
2395 pub fn parse_count(&self) -> usize {
2396 self.parse_count
2397 }
2398
2399 pub fn selections_update_count(&self) -> usize {
2400 self.selections_update_count
2401 }
2402}
2403
2404impl Clone for BufferSnapshot {
2405 fn clone(&self) -> Self {
2406 Self {
2407 text: self.text.clone(),
2408 tree: self.tree.clone(),
2409 remote_selections: self.remote_selections.clone(),
2410 diagnostics: self.diagnostics.clone(),
2411 selections_update_count: self.selections_update_count,
2412 diagnostics_update_count: self.diagnostics_update_count,
2413 is_parsing: self.is_parsing,
2414 language: self.language.clone(),
2415 parse_count: self.parse_count,
2416 }
2417 }
2418}
2419
2420impl Deref for BufferSnapshot {
2421 type Target = text::BufferSnapshot;
2422
2423 fn deref(&self) -> &Self::Target {
2424 &self.text
2425 }
2426}
2427
2428impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
2429 type I = ByteChunks<'a>;
2430
2431 fn text(&mut self, node: tree_sitter::Node) -> Self::I {
2432 ByteChunks(self.0.chunks_in_range(node.byte_range()))
2433 }
2434}
2435
2436struct ByteChunks<'a>(rope::Chunks<'a>);
2437
2438impl<'a> Iterator for ByteChunks<'a> {
2439 type Item = &'a [u8];
2440
2441 fn next(&mut self) -> Option<Self::Item> {
2442 self.0.next().map(str::as_bytes)
2443 }
2444}
2445
2446unsafe impl<'a> Send for BufferChunks<'a> {}
2447
2448impl<'a> BufferChunks<'a> {
2449 pub fn seek(&mut self, offset: usize) {
2450 self.range.start = offset;
2451 self.chunks.seek(self.range.start);
2452 if let Some(highlights) = self.highlights.as_mut() {
2453 highlights
2454 .stack
2455 .retain(|(end_offset, _)| *end_offset > offset);
2456 if let Some((mat, capture_ix)) = &highlights.next_capture {
2457 let capture = mat.captures[*capture_ix as usize];
2458 if offset >= capture.node.start_byte() {
2459 let next_capture_end = capture.node.end_byte();
2460 if offset < next_capture_end {
2461 highlights.stack.push((
2462 next_capture_end,
2463 highlights.highlight_map.get(capture.index),
2464 ));
2465 }
2466 highlights.next_capture.take();
2467 }
2468 }
2469 highlights.captures.set_byte_range(self.range.clone());
2470 }
2471 }
2472
2473 pub fn offset(&self) -> usize {
2474 self.range.start
2475 }
2476
2477 fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
2478 let depth = match endpoint.severity {
2479 DiagnosticSeverity::ERROR => &mut self.error_depth,
2480 DiagnosticSeverity::WARNING => &mut self.warning_depth,
2481 DiagnosticSeverity::INFORMATION => &mut self.information_depth,
2482 DiagnosticSeverity::HINT => &mut self.hint_depth,
2483 _ => return,
2484 };
2485 if endpoint.is_start {
2486 *depth += 1;
2487 } else {
2488 *depth -= 1;
2489 }
2490 }
2491
2492 fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
2493 if self.error_depth > 0 {
2494 Some(DiagnosticSeverity::ERROR)
2495 } else if self.warning_depth > 0 {
2496 Some(DiagnosticSeverity::WARNING)
2497 } else if self.information_depth > 0 {
2498 Some(DiagnosticSeverity::INFORMATION)
2499 } else if self.hint_depth > 0 {
2500 Some(DiagnosticSeverity::HINT)
2501 } else {
2502 None
2503 }
2504 }
2505}
2506
2507impl<'a> Iterator for BufferChunks<'a> {
2508 type Item = Chunk<'a>;
2509
2510 fn next(&mut self) -> Option<Self::Item> {
2511 let mut next_capture_start = usize::MAX;
2512 let mut next_diagnostic_endpoint = usize::MAX;
2513
2514 if let Some(highlights) = self.highlights.as_mut() {
2515 while let Some((parent_capture_end, _)) = highlights.stack.last() {
2516 if *parent_capture_end <= self.range.start {
2517 highlights.stack.pop();
2518 } else {
2519 break;
2520 }
2521 }
2522
2523 if highlights.next_capture.is_none() {
2524 highlights.next_capture = highlights.captures.next();
2525 }
2526
2527 while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
2528 let capture = mat.captures[*capture_ix as usize];
2529 if self.range.start < capture.node.start_byte() {
2530 next_capture_start = capture.node.start_byte();
2531 break;
2532 } else {
2533 let highlight_id = highlights.highlight_map.get(capture.index);
2534 highlights
2535 .stack
2536 .push((capture.node.end_byte(), highlight_id));
2537 highlights.next_capture = highlights.captures.next();
2538 }
2539 }
2540 }
2541
2542 while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
2543 if endpoint.offset <= self.range.start {
2544 self.update_diagnostic_depths(endpoint);
2545 self.diagnostic_endpoints.next();
2546 } else {
2547 next_diagnostic_endpoint = endpoint.offset;
2548 break;
2549 }
2550 }
2551
2552 if let Some(chunk) = self.chunks.peek() {
2553 let chunk_start = self.range.start;
2554 let mut chunk_end = (self.chunks.offset() + chunk.len())
2555 .min(next_capture_start)
2556 .min(next_diagnostic_endpoint);
2557 let mut highlight_style = None;
2558 if let Some(highlights) = self.highlights.as_ref() {
2559 if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
2560 chunk_end = chunk_end.min(*parent_capture_end);
2561 highlight_style = parent_highlight_id.style(highlights.theme);
2562 }
2563 }
2564
2565 let slice =
2566 &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2567 self.range.start = chunk_end;
2568 if self.range.start == self.chunks.offset() + chunk.len() {
2569 self.chunks.next().unwrap();
2570 }
2571
2572 Some(Chunk {
2573 text: slice,
2574 highlight_style,
2575 diagnostic: self.current_diagnostic_severity(),
2576 })
2577 } else {
2578 None
2579 }
2580 }
2581}
2582
2583impl QueryCursorHandle {
2584 pub(crate) fn new() -> Self {
2585 QueryCursorHandle(Some(
2586 QUERY_CURSORS
2587 .lock()
2588 .pop()
2589 .unwrap_or_else(|| QueryCursor::new()),
2590 ))
2591 }
2592}
2593
2594impl Deref for QueryCursorHandle {
2595 type Target = QueryCursor;
2596
2597 fn deref(&self) -> &Self::Target {
2598 self.0.as_ref().unwrap()
2599 }
2600}
2601
2602impl DerefMut for QueryCursorHandle {
2603 fn deref_mut(&mut self) -> &mut Self::Target {
2604 self.0.as_mut().unwrap()
2605 }
2606}
2607
2608impl Drop for QueryCursorHandle {
2609 fn drop(&mut self) {
2610 let mut cursor = self.0.take().unwrap();
2611 cursor.set_byte_range(0..usize::MAX);
2612 cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
2613 QUERY_CURSORS.lock().push(cursor)
2614 }
2615}
2616
2617trait ToTreeSitterPoint {
2618 fn to_ts_point(self) -> tree_sitter::Point;
2619 fn from_ts_point(point: tree_sitter::Point) -> Self;
2620}
2621
2622impl ToTreeSitterPoint for Point {
2623 fn to_ts_point(self) -> tree_sitter::Point {
2624 tree_sitter::Point::new(self.row as usize, self.column as usize)
2625 }
2626
2627 fn from_ts_point(point: tree_sitter::Point) -> Self {
2628 Point::new(point.row as u32, point.column as u32)
2629 }
2630}
2631
2632impl operation_queue::Operation for Operation {
2633 fn lamport_timestamp(&self) -> clock::Lamport {
2634 match self {
2635 Operation::Buffer(_) => {
2636 unreachable!("buffer operations should never be deferred at this layer")
2637 }
2638 Operation::UpdateDiagnostics {
2639 lamport_timestamp, ..
2640 }
2641 | Operation::UpdateSelections {
2642 lamport_timestamp, ..
2643 } => *lamport_timestamp,
2644 Operation::UpdateCompletionTriggers { .. } => {
2645 unreachable!("updating completion triggers should never be deferred")
2646 }
2647 }
2648 }
2649}
2650
2651impl Default for Diagnostic {
2652 fn default() -> Self {
2653 Self {
2654 code: Default::default(),
2655 severity: DiagnosticSeverity::ERROR,
2656 message: Default::default(),
2657 group_id: Default::default(),
2658 is_primary: Default::default(),
2659 is_valid: true,
2660 is_disk_based: false,
2661 }
2662 }
2663}
2664
2665impl<T> Completion<T> {
2666 pub fn label(&self) -> &str {
2667 &self.lsp_completion.label
2668 }
2669
2670 pub fn filter_range(&self) -> Range<usize> {
2671 if let Some(filter_text) = self.lsp_completion.filter_text.as_deref() {
2672 if let Some(start) = self.label().find(filter_text) {
2673 start..start + filter_text.len()
2674 } else {
2675 0..self.label().len()
2676 }
2677 } else {
2678 0..self.label().len()
2679 }
2680 }
2681
2682 pub fn sort_key(&self) -> (usize, &str) {
2683 let kind_key = match self.lsp_completion.kind {
2684 Some(lsp::CompletionItemKind::VARIABLE) => 0,
2685 _ => 1,
2686 };
2687 (kind_key, &self.label()[self.filter_range()])
2688 }
2689
2690 pub fn is_snippet(&self) -> bool {
2691 self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
2692 }
2693}
2694
2695pub fn contiguous_ranges(
2696 values: impl Iterator<Item = u32>,
2697 max_len: usize,
2698) -> impl Iterator<Item = Range<u32>> {
2699 let mut values = values.into_iter();
2700 let mut current_range: Option<Range<u32>> = None;
2701 std::iter::from_fn(move || loop {
2702 if let Some(value) = values.next() {
2703 if let Some(range) = &mut current_range {
2704 if value == range.end && range.len() < max_len {
2705 range.end += 1;
2706 continue;
2707 }
2708 }
2709
2710 let prev_range = current_range.clone();
2711 current_range = Some(value..(value + 1));
2712 if prev_range.is_some() {
2713 return prev_range;
2714 }
2715 } else {
2716 return current_range.take();
2717 }
2718 })
2719}