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