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 = this.version.gt(&parsed_version) || grammar_changed;
729 this.parsing_in_background = false;
730 this.did_finish_parsing(new_tree, parsed_version, cx);
731
732 if parse_again && this.reparse(cx) {
733 return;
734 }
735 });
736 })
737 .detach();
738 }
739 }
740 }
741 false
742 }
743
744 fn parse_text(text: &Rope, old_tree: Option<Tree>, grammar: &Grammar) -> Tree {
745 PARSER.with(|parser| {
746 let mut parser = parser.borrow_mut();
747 parser
748 .set_language(grammar.ts_language)
749 .expect("incompatible grammar");
750 let mut chunks = text.chunks_in_range(0..text.len());
751 let tree = parser
752 .parse_with(
753 &mut move |offset, _| {
754 chunks.seek(offset);
755 chunks.next().unwrap_or("").as_bytes()
756 },
757 old_tree.as_ref(),
758 )
759 .unwrap();
760 tree
761 })
762 }
763
764 fn interpolate_tree(&self, tree: &mut SyntaxTree) {
765 for edit in self.edits_since::<(usize, Point)>(&tree.version) {
766 let (bytes, lines) = edit.flatten();
767 tree.tree.edit(&InputEdit {
768 start_byte: bytes.new.start,
769 old_end_byte: bytes.new.start + bytes.old.len(),
770 new_end_byte: bytes.new.end,
771 start_position: lines.new.start.to_ts_point(),
772 old_end_position: (lines.new.start + (lines.old.end - lines.old.start))
773 .to_ts_point(),
774 new_end_position: lines.new.end.to_ts_point(),
775 });
776 }
777 tree.version = self.version();
778 }
779
780 fn did_finish_parsing(
781 &mut self,
782 tree: Tree,
783 version: clock::Global,
784 cx: &mut ModelContext<Self>,
785 ) {
786 self.parse_count += 1;
787 *self.syntax_tree.lock() = Some(SyntaxTree { tree, version });
788 self.request_autoindent(cx);
789 cx.emit(Event::Reparsed);
790 cx.notify();
791 }
792
793 pub fn update_diagnostics<T>(
794 &mut self,
795 provider_name: Arc<str>,
796 version: Option<i32>,
797 mut diagnostics: Vec<DiagnosticEntry<T>>,
798 cx: &mut ModelContext<Self>,
799 ) -> Result<Operation>
800 where
801 T: Copy + Ord + TextDimension + Sub<Output = T> + Clip + ToPoint,
802 {
803 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
804 Ordering::Equal
805 .then_with(|| b.is_primary.cmp(&a.is_primary))
806 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
807 .then_with(|| a.severity.cmp(&b.severity))
808 .then_with(|| a.message.cmp(&b.message))
809 }
810
811 let version = version.map(|version| version as usize);
812 let content = if let Some(version) = version {
813 let language_server = self.language_server.as_mut().unwrap();
814 language_server
815 .pending_snapshots
816 .retain(|&v, _| v >= version);
817 let snapshot = language_server
818 .pending_snapshots
819 .get(&version)
820 .ok_or_else(|| anyhow!("missing snapshot"))?;
821 &snapshot.buffer_snapshot
822 } else {
823 self.deref()
824 };
825
826 diagnostics.sort_unstable_by(|a, b| {
827 Ordering::Equal
828 .then_with(|| a.range.start.cmp(&b.range.start))
829 .then_with(|| b.range.end.cmp(&a.range.end))
830 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
831 });
832
833 let mut sanitized_diagnostics = Vec::new();
834 let mut edits_since_save = content.edits_since::<T>(&self.saved_version).peekable();
835 let mut last_edit_old_end = T::default();
836 let mut last_edit_new_end = T::default();
837 'outer: for entry in diagnostics {
838 let mut start = entry.range.start;
839 let mut end = entry.range.end;
840
841 // Some diagnostics are based on files on disk instead of buffers'
842 // current contents. Adjust these diagnostics' ranges to reflect
843 // any unsaved edits.
844 if entry.diagnostic.is_disk_based {
845 while let Some(edit) = edits_since_save.peek() {
846 if edit.old.end <= start {
847 last_edit_old_end = edit.old.end;
848 last_edit_new_end = edit.new.end;
849 edits_since_save.next();
850 } else if edit.old.start <= end && edit.old.end >= start {
851 continue 'outer;
852 } else {
853 break;
854 }
855 }
856
857 let start_overshoot = start - last_edit_old_end;
858 start = last_edit_new_end;
859 start.add_assign(&start_overshoot);
860
861 let end_overshoot = end - last_edit_old_end;
862 end = last_edit_new_end;
863 end.add_assign(&end_overshoot);
864 }
865
866 let range = start.clip(Bias::Left, content)..end.clip(Bias::Right, content);
867 let mut range = range.start.to_point(content)..range.end.to_point(content);
868 // Expand empty ranges by one character
869 if range.start == range.end {
870 range.end.column += 1;
871 range.end = content.clip_point(range.end, Bias::Right);
872 if range.start == range.end && range.end.column > 0 {
873 range.start.column -= 1;
874 range.start = content.clip_point(range.start, Bias::Left);
875 }
876 }
877
878 sanitized_diagnostics.push(DiagnosticEntry {
879 range,
880 diagnostic: entry.diagnostic,
881 });
882 }
883 drop(edits_since_save);
884
885 let set = DiagnosticSet::new(provider_name, sanitized_diagnostics, content);
886 self.apply_diagnostic_update(set.clone(), cx);
887 Ok(Operation::UpdateDiagnostics {
888 provider_name: set.provider_name().to_string(),
889 diagnostics: set.iter().cloned().collect(),
890 lamport_timestamp: self.text.lamport_clock.tick(),
891 })
892 }
893
894 fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
895 if let Some(indent_columns) = self.compute_autoindents() {
896 let indent_columns = cx.background().spawn(indent_columns);
897 match cx
898 .background()
899 .block_with_timeout(Duration::from_micros(500), indent_columns)
900 {
901 Ok(indent_columns) => self.apply_autoindents(indent_columns, cx),
902 Err(indent_columns) => {
903 self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
904 let indent_columns = indent_columns.await;
905 this.update(&mut cx, |this, cx| {
906 this.apply_autoindents(indent_columns, cx);
907 });
908 }));
909 }
910 }
911 }
912 }
913
914 fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, u32>>> {
915 let max_rows_between_yields = 100;
916 let snapshot = self.snapshot();
917 if snapshot.language.is_none()
918 || snapshot.tree.is_none()
919 || self.autoindent_requests.is_empty()
920 {
921 return None;
922 }
923
924 let autoindent_requests = self.autoindent_requests.clone();
925 Some(async move {
926 let mut indent_columns = BTreeMap::new();
927 for request in autoindent_requests {
928 let old_to_new_rows = request
929 .edited
930 .iter()
931 .map(|anchor| anchor.summary::<Point>(&request.before_edit).row)
932 .zip(
933 request
934 .edited
935 .iter()
936 .map(|anchor| anchor.summary::<Point>(&snapshot).row),
937 )
938 .collect::<BTreeMap<u32, u32>>();
939
940 let mut old_suggestions = HashMap::<u32, u32>::default();
941 let old_edited_ranges =
942 contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
943 for old_edited_range in old_edited_ranges {
944 let suggestions = request
945 .before_edit
946 .suggest_autoindents(old_edited_range.clone())
947 .into_iter()
948 .flatten();
949 for (old_row, suggestion) in old_edited_range.zip(suggestions) {
950 let indentation_basis = old_to_new_rows
951 .get(&suggestion.basis_row)
952 .and_then(|from_row| old_suggestions.get(from_row).copied())
953 .unwrap_or_else(|| {
954 request
955 .before_edit
956 .indent_column_for_line(suggestion.basis_row)
957 });
958 let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
959 old_suggestions.insert(
960 *old_to_new_rows.get(&old_row).unwrap(),
961 indentation_basis + delta,
962 );
963 }
964 yield_now().await;
965 }
966
967 // At this point, old_suggestions contains the suggested indentation for all edited lines with respect to the state of the
968 // buffer before the edit, but keyed by the row for these lines after the edits were applied.
969 let new_edited_row_ranges =
970 contiguous_ranges(old_to_new_rows.values().copied(), max_rows_between_yields);
971 for new_edited_row_range in new_edited_row_ranges {
972 let suggestions = snapshot
973 .suggest_autoindents(new_edited_row_range.clone())
974 .into_iter()
975 .flatten();
976 for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
977 let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
978 let new_indentation = indent_columns
979 .get(&suggestion.basis_row)
980 .copied()
981 .unwrap_or_else(|| {
982 snapshot.indent_column_for_line(suggestion.basis_row)
983 })
984 + delta;
985 if old_suggestions
986 .get(&new_row)
987 .map_or(true, |old_indentation| new_indentation != *old_indentation)
988 {
989 indent_columns.insert(new_row, new_indentation);
990 }
991 }
992 yield_now().await;
993 }
994
995 if let Some(inserted) = request.inserted.as_ref() {
996 let inserted_row_ranges = contiguous_ranges(
997 inserted
998 .iter()
999 .map(|range| range.to_point(&snapshot))
1000 .flat_map(|range| range.start.row..range.end.row + 1),
1001 max_rows_between_yields,
1002 );
1003 for inserted_row_range in inserted_row_ranges {
1004 let suggestions = snapshot
1005 .suggest_autoindents(inserted_row_range.clone())
1006 .into_iter()
1007 .flatten();
1008 for (row, suggestion) in inserted_row_range.zip(suggestions) {
1009 let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
1010 let new_indentation = indent_columns
1011 .get(&suggestion.basis_row)
1012 .copied()
1013 .unwrap_or_else(|| {
1014 snapshot.indent_column_for_line(suggestion.basis_row)
1015 })
1016 + delta;
1017 indent_columns.insert(row, new_indentation);
1018 }
1019 yield_now().await;
1020 }
1021 }
1022 }
1023 indent_columns
1024 })
1025 }
1026
1027 fn apply_autoindents(
1028 &mut self,
1029 indent_columns: BTreeMap<u32, u32>,
1030 cx: &mut ModelContext<Self>,
1031 ) {
1032 self.autoindent_requests.clear();
1033 self.start_transaction();
1034 for (row, indent_column) in &indent_columns {
1035 self.set_indent_column_for_line(*row, *indent_column, cx);
1036 }
1037 self.end_transaction(cx);
1038 }
1039
1040 fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
1041 let current_column = self.indent_column_for_line(row);
1042 if column > current_column {
1043 let offset = Point::new(row, 0).to_offset(&*self);
1044 self.edit(
1045 [offset..offset],
1046 " ".repeat((column - current_column) as usize),
1047 cx,
1048 );
1049 } else if column < current_column {
1050 self.edit(
1051 [Point::new(row, 0)..Point::new(row, current_column - column)],
1052 "",
1053 cx,
1054 );
1055 }
1056 }
1057
1058 pub(crate) fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
1059 // TODO: it would be nice to not allocate here.
1060 let old_text = self.text();
1061 let base_version = self.version();
1062 cx.background().spawn(async move {
1063 let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1064 .iter_all_changes()
1065 .map(|c| (c.tag(), c.value().len()))
1066 .collect::<Vec<_>>();
1067 Diff {
1068 base_version,
1069 new_text,
1070 changes,
1071 }
1072 })
1073 }
1074
1075 pub(crate) fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1076 if self.version == diff.base_version {
1077 self.start_transaction();
1078 let mut offset = 0;
1079 for (tag, len) in diff.changes {
1080 let range = offset..(offset + len);
1081 match tag {
1082 ChangeTag::Equal => offset += len,
1083 ChangeTag::Delete => self.edit(Some(range), "", cx),
1084 ChangeTag::Insert => {
1085 self.edit(Some(offset..offset), &diff.new_text[range], cx);
1086 offset += len;
1087 }
1088 }
1089 }
1090 self.end_transaction(cx);
1091 true
1092 } else {
1093 false
1094 }
1095 }
1096
1097 pub fn is_dirty(&self) -> bool {
1098 !self.saved_version.ge(&self.version)
1099 || self.file.as_ref().map_or(false, |file| file.is_deleted())
1100 }
1101
1102 pub fn has_conflict(&self) -> bool {
1103 !self.saved_version.ge(&self.version)
1104 && self
1105 .file
1106 .as_ref()
1107 .map_or(false, |file| file.mtime() > self.saved_mtime)
1108 }
1109
1110 pub fn subscribe(&mut self) -> Subscription {
1111 self.text.subscribe()
1112 }
1113
1114 pub fn start_transaction(&mut self) -> Option<TransactionId> {
1115 self.start_transaction_at(Instant::now())
1116 }
1117
1118 pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1119 self.text.start_transaction_at(now)
1120 }
1121
1122 pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1123 self.end_transaction_at(Instant::now(), cx)
1124 }
1125
1126 pub fn end_transaction_at(
1127 &mut self,
1128 now: Instant,
1129 cx: &mut ModelContext<Self>,
1130 ) -> Option<TransactionId> {
1131 if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1132 let was_dirty = start_version != self.saved_version;
1133 self.did_edit(&start_version, was_dirty, cx);
1134 Some(transaction_id)
1135 } else {
1136 None
1137 }
1138 }
1139
1140 pub fn set_active_selections(
1141 &mut self,
1142 selections: Arc<[Selection<Anchor>]>,
1143 cx: &mut ModelContext<Self>,
1144 ) {
1145 let lamport_timestamp = self.text.lamport_clock.tick();
1146 self.remote_selections.insert(
1147 self.text.replica_id(),
1148 SelectionSet {
1149 selections: selections.clone(),
1150 lamport_timestamp,
1151 },
1152 );
1153 self.send_operation(
1154 Operation::UpdateSelections {
1155 replica_id: self.text.replica_id(),
1156 selections,
1157 lamport_timestamp,
1158 },
1159 cx,
1160 );
1161 }
1162
1163 pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1164 self.set_active_selections(Arc::from([]), cx);
1165 }
1166
1167 fn update_language_server(&mut self) {
1168 let language_server = if let Some(language_server) = self.language_server.as_mut() {
1169 language_server
1170 } else {
1171 return;
1172 };
1173 let abs_path = self
1174 .file
1175 .as_ref()
1176 .map_or(Path::new("/").to_path_buf(), |file| {
1177 file.abs_path().unwrap()
1178 });
1179
1180 let version = post_inc(&mut language_server.next_version);
1181 let snapshot = LanguageServerSnapshot {
1182 buffer_snapshot: self.text.snapshot(),
1183 version,
1184 path: Arc::from(abs_path),
1185 };
1186 language_server
1187 .pending_snapshots
1188 .insert(version, snapshot.clone());
1189 let _ = language_server
1190 .latest_snapshot
1191 .blocking_send(Some(snapshot));
1192 }
1193
1194 pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, cx: &mut ModelContext<Self>)
1195 where
1196 I: IntoIterator<Item = Range<S>>,
1197 S: ToOffset,
1198 T: Into<String>,
1199 {
1200 self.edit_internal(ranges_iter, new_text, false, cx)
1201 }
1202
1203 pub fn edit_with_autoindent<I, S, T>(
1204 &mut self,
1205 ranges_iter: I,
1206 new_text: T,
1207 cx: &mut ModelContext<Self>,
1208 ) where
1209 I: IntoIterator<Item = Range<S>>,
1210 S: ToOffset,
1211 T: Into<String>,
1212 {
1213 self.edit_internal(ranges_iter, new_text, true, cx)
1214 }
1215
1216 pub fn edit_internal<I, S, T>(
1217 &mut self,
1218 ranges_iter: I,
1219 new_text: T,
1220 autoindent: bool,
1221 cx: &mut ModelContext<Self>,
1222 ) where
1223 I: IntoIterator<Item = Range<S>>,
1224 S: ToOffset,
1225 T: Into<String>,
1226 {
1227 let new_text = new_text.into();
1228
1229 // Skip invalid ranges and coalesce contiguous ones.
1230 let mut ranges: Vec<Range<usize>> = Vec::new();
1231 for range in ranges_iter {
1232 let range = range.start.to_offset(self)..range.end.to_offset(self);
1233 if !new_text.is_empty() || !range.is_empty() {
1234 if let Some(prev_range) = ranges.last_mut() {
1235 if prev_range.end >= range.start {
1236 prev_range.end = cmp::max(prev_range.end, range.end);
1237 } else {
1238 ranges.push(range);
1239 }
1240 } else {
1241 ranges.push(range);
1242 }
1243 }
1244 }
1245 if ranges.is_empty() {
1246 return;
1247 }
1248
1249 self.start_transaction();
1250 self.pending_autoindent.take();
1251 let autoindent_request = if autoindent && self.language.is_some() {
1252 let before_edit = self.snapshot();
1253 let edited = ranges
1254 .iter()
1255 .filter_map(|range| {
1256 let start = range.start.to_point(self);
1257 if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1258 None
1259 } else {
1260 Some(self.anchor_before(range.start))
1261 }
1262 })
1263 .collect();
1264 Some((before_edit, edited))
1265 } else {
1266 None
1267 };
1268
1269 let first_newline_ix = new_text.find('\n');
1270 let new_text_len = new_text.len();
1271
1272 let edit = self.text.edit(ranges.iter().cloned(), new_text);
1273
1274 if let Some((before_edit, edited)) = autoindent_request {
1275 let mut inserted = None;
1276 if let Some(first_newline_ix) = first_newline_ix {
1277 let mut delta = 0isize;
1278 inserted = Some(
1279 ranges
1280 .iter()
1281 .map(|range| {
1282 let start =
1283 (delta + range.start as isize) as usize + first_newline_ix + 1;
1284 let end = (delta + range.start as isize) as usize + new_text_len;
1285 delta +=
1286 (range.end as isize - range.start as isize) + new_text_len as isize;
1287 self.anchor_before(start)..self.anchor_after(end)
1288 })
1289 .collect(),
1290 );
1291 }
1292
1293 self.autoindent_requests.push(Arc::new(AutoindentRequest {
1294 before_edit,
1295 edited,
1296 inserted,
1297 }));
1298 }
1299
1300 self.end_transaction(cx);
1301 self.send_operation(Operation::Buffer(text::Operation::Edit(edit)), cx);
1302 }
1303
1304 fn did_edit(
1305 &mut self,
1306 old_version: &clock::Global,
1307 was_dirty: bool,
1308 cx: &mut ModelContext<Self>,
1309 ) {
1310 if self.edits_since::<usize>(old_version).next().is_none() {
1311 return;
1312 }
1313
1314 self.reparse(cx);
1315 self.update_language_server();
1316
1317 cx.emit(Event::Edited);
1318 if !was_dirty {
1319 cx.emit(Event::Dirtied);
1320 }
1321 cx.notify();
1322 }
1323
1324 fn grammar(&self) -> Option<&Arc<Grammar>> {
1325 self.language.as_ref().and_then(|l| l.grammar.as_ref())
1326 }
1327
1328 pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1329 &mut self,
1330 ops: I,
1331 cx: &mut ModelContext<Self>,
1332 ) -> Result<()> {
1333 self.pending_autoindent.take();
1334 let was_dirty = self.is_dirty();
1335 let old_version = self.version.clone();
1336 let mut deferred_ops = Vec::new();
1337 let buffer_ops = ops
1338 .into_iter()
1339 .filter_map(|op| match op {
1340 Operation::Buffer(op) => Some(op),
1341 _ => {
1342 if self.can_apply_op(&op) {
1343 self.apply_op(op, cx);
1344 } else {
1345 deferred_ops.push(op);
1346 }
1347 None
1348 }
1349 })
1350 .collect::<Vec<_>>();
1351 self.text.apply_ops(buffer_ops)?;
1352 self.deferred_ops.insert(deferred_ops);
1353 self.flush_deferred_ops(cx);
1354 self.did_edit(&old_version, was_dirty, cx);
1355 // Notify independently of whether the buffer was edited as the operations could include a
1356 // selection update.
1357 cx.notify();
1358 Ok(())
1359 }
1360
1361 fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1362 let mut deferred_ops = Vec::new();
1363 for op in self.deferred_ops.drain().iter().cloned() {
1364 if self.can_apply_op(&op) {
1365 self.apply_op(op, cx);
1366 } else {
1367 deferred_ops.push(op);
1368 }
1369 }
1370 self.deferred_ops.insert(deferred_ops);
1371 }
1372
1373 fn can_apply_op(&self, operation: &Operation) -> bool {
1374 match operation {
1375 Operation::Buffer(_) => {
1376 unreachable!("buffer operations should never be applied at this layer")
1377 }
1378 Operation::UpdateDiagnostics {
1379 diagnostics: diagnostic_set,
1380 ..
1381 } => diagnostic_set.iter().all(|diagnostic| {
1382 self.text.can_resolve(&diagnostic.range.start)
1383 && self.text.can_resolve(&diagnostic.range.end)
1384 }),
1385 Operation::UpdateSelections { selections, .. } => selections
1386 .iter()
1387 .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1388 }
1389 }
1390
1391 fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1392 match operation {
1393 Operation::Buffer(_) => {
1394 unreachable!("buffer operations should never be applied at this layer")
1395 }
1396 Operation::UpdateDiagnostics {
1397 provider_name,
1398 diagnostics: diagnostic_set,
1399 ..
1400 } => {
1401 let snapshot = self.snapshot();
1402 self.apply_diagnostic_update(
1403 DiagnosticSet::from_sorted_entries(
1404 provider_name,
1405 diagnostic_set.iter().cloned(),
1406 &snapshot,
1407 ),
1408 cx,
1409 );
1410 }
1411 Operation::UpdateSelections {
1412 replica_id,
1413 selections,
1414 lamport_timestamp,
1415 } => {
1416 if let Some(set) = self.remote_selections.get(&replica_id) {
1417 if set.lamport_timestamp > lamport_timestamp {
1418 return;
1419 }
1420 }
1421
1422 self.remote_selections.insert(
1423 replica_id,
1424 SelectionSet {
1425 selections,
1426 lamport_timestamp,
1427 },
1428 );
1429 self.text.lamport_clock.observe(lamport_timestamp);
1430 self.selections_update_count += 1;
1431 }
1432 }
1433 }
1434
1435 fn apply_diagnostic_update(&mut self, set: DiagnosticSet, cx: &mut ModelContext<Self>) {
1436 match self
1437 .diagnostic_sets
1438 .binary_search_by_key(&set.provider_name(), |set| set.provider_name())
1439 {
1440 Ok(ix) => self.diagnostic_sets[ix] = set.clone(),
1441 Err(ix) => self.diagnostic_sets.insert(ix, set.clone()),
1442 }
1443
1444 self.diagnostics_update_count += 1;
1445 cx.notify();
1446 cx.emit(Event::DiagnosticsUpdated);
1447 }
1448
1449 #[cfg(not(test))]
1450 pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1451 if let Some(file) = &self.file {
1452 file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1453 }
1454 }
1455
1456 #[cfg(test)]
1457 pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1458 self.operations.push(operation);
1459 }
1460
1461 pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1462 self.remote_selections.remove(&replica_id);
1463 cx.notify();
1464 }
1465
1466 pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1467 let was_dirty = self.is_dirty();
1468 let old_version = self.version.clone();
1469
1470 if let Some((transaction_id, operation)) = self.text.undo() {
1471 self.send_operation(Operation::Buffer(operation), cx);
1472 self.did_edit(&old_version, was_dirty, cx);
1473 Some(transaction_id)
1474 } else {
1475 None
1476 }
1477 }
1478
1479 pub fn undo_transaction(
1480 &mut self,
1481 transaction_id: TransactionId,
1482 cx: &mut ModelContext<Self>,
1483 ) -> bool {
1484 let was_dirty = self.is_dirty();
1485 let old_version = self.version.clone();
1486
1487 if let Some(operation) = self.text.undo_transaction(transaction_id) {
1488 self.send_operation(Operation::Buffer(operation), cx);
1489 self.did_edit(&old_version, was_dirty, cx);
1490 true
1491 } else {
1492 false
1493 }
1494 }
1495
1496 pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1497 let was_dirty = self.is_dirty();
1498 let old_version = self.version.clone();
1499
1500 if let Some((transaction_id, operation)) = self.text.redo() {
1501 self.send_operation(Operation::Buffer(operation), cx);
1502 self.did_edit(&old_version, was_dirty, cx);
1503 Some(transaction_id)
1504 } else {
1505 None
1506 }
1507 }
1508
1509 pub fn redo_transaction(
1510 &mut self,
1511 transaction_id: TransactionId,
1512 cx: &mut ModelContext<Self>,
1513 ) -> bool {
1514 let was_dirty = self.is_dirty();
1515 let old_version = self.version.clone();
1516
1517 if let Some(operation) = self.text.redo_transaction(transaction_id) {
1518 self.send_operation(Operation::Buffer(operation), cx);
1519 self.did_edit(&old_version, was_dirty, cx);
1520 true
1521 } else {
1522 false
1523 }
1524 }
1525}
1526
1527#[cfg(any(test, feature = "test-support"))]
1528impl Buffer {
1529 pub fn set_group_interval(&mut self, group_interval: Duration) {
1530 self.text.set_group_interval(group_interval);
1531 }
1532
1533 pub fn randomly_edit<T>(
1534 &mut self,
1535 rng: &mut T,
1536 old_range_count: usize,
1537 cx: &mut ModelContext<Self>,
1538 ) where
1539 T: rand::Rng,
1540 {
1541 let mut old_ranges: Vec<Range<usize>> = Vec::new();
1542 for _ in 0..old_range_count {
1543 let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1544 if last_end > self.len() {
1545 break;
1546 }
1547 old_ranges.push(self.text.random_byte_range(last_end, rng));
1548 }
1549 let new_text_len = rng.gen_range(0..10);
1550 let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1551 .take(new_text_len)
1552 .collect();
1553 log::info!(
1554 "mutating buffer {} at {:?}: {:?}",
1555 self.replica_id(),
1556 old_ranges,
1557 new_text
1558 );
1559 self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1560 }
1561
1562 pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1563 let was_dirty = self.is_dirty();
1564 let old_version = self.version.clone();
1565
1566 let ops = self.text.randomly_undo_redo(rng);
1567 if !ops.is_empty() {
1568 for op in ops {
1569 self.send_operation(Operation::Buffer(op), cx);
1570 self.did_edit(&old_version, was_dirty, cx);
1571 }
1572 }
1573 }
1574}
1575
1576impl Entity for Buffer {
1577 type Event = Event;
1578
1579 fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1580 if let Some(file) = self.file.as_ref() {
1581 file.buffer_removed(self.remote_id(), cx);
1582 }
1583 }
1584}
1585
1586impl Deref for Buffer {
1587 type Target = TextBuffer;
1588
1589 fn deref(&self) -> &Self::Target {
1590 &self.text
1591 }
1592}
1593
1594impl BufferSnapshot {
1595 fn suggest_autoindents<'a>(
1596 &'a self,
1597 row_range: Range<u32>,
1598 ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1599 let mut query_cursor = QueryCursorHandle::new();
1600 if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1601 let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1602
1603 // Get the "indentation ranges" that intersect this row range.
1604 let indent_capture_ix = grammar.indents_query.capture_index_for_name("indent");
1605 let end_capture_ix = grammar.indents_query.capture_index_for_name("end");
1606 query_cursor.set_point_range(
1607 Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1608 ..Point::new(row_range.end, 0).to_ts_point(),
1609 );
1610 let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1611 for mat in query_cursor.matches(
1612 &grammar.indents_query,
1613 tree.root_node(),
1614 TextProvider(self.as_rope()),
1615 ) {
1616 let mut node_kind = "";
1617 let mut start: Option<Point> = None;
1618 let mut end: Option<Point> = None;
1619 for capture in mat.captures {
1620 if Some(capture.index) == indent_capture_ix {
1621 node_kind = capture.node.kind();
1622 start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1623 end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1624 } else if Some(capture.index) == end_capture_ix {
1625 end = Some(Point::from_ts_point(capture.node.start_position().into()));
1626 }
1627 }
1628
1629 if let Some((start, end)) = start.zip(end) {
1630 if start.row == end.row {
1631 continue;
1632 }
1633
1634 let range = start..end;
1635 match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1636 Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1637 Ok(ix) => {
1638 let prev_range = &mut indentation_ranges[ix];
1639 prev_range.0.end = prev_range.0.end.max(range.end);
1640 }
1641 }
1642 }
1643 }
1644
1645 let mut prev_row = prev_non_blank_row.unwrap_or(0);
1646 Some(row_range.map(move |row| {
1647 let row_start = Point::new(row, self.indent_column_for_line(row));
1648
1649 let mut indent_from_prev_row = false;
1650 let mut outdent_to_row = u32::MAX;
1651 for (range, _node_kind) in &indentation_ranges {
1652 if range.start.row >= row {
1653 break;
1654 }
1655
1656 if range.start.row == prev_row && range.end > row_start {
1657 indent_from_prev_row = true;
1658 }
1659 if range.end.row >= prev_row && range.end <= row_start {
1660 outdent_to_row = outdent_to_row.min(range.start.row);
1661 }
1662 }
1663
1664 let suggestion = if outdent_to_row == prev_row {
1665 IndentSuggestion {
1666 basis_row: prev_row,
1667 indent: false,
1668 }
1669 } else if indent_from_prev_row {
1670 IndentSuggestion {
1671 basis_row: prev_row,
1672 indent: true,
1673 }
1674 } else if outdent_to_row < prev_row {
1675 IndentSuggestion {
1676 basis_row: outdent_to_row,
1677 indent: false,
1678 }
1679 } else {
1680 IndentSuggestion {
1681 basis_row: prev_row,
1682 indent: false,
1683 }
1684 };
1685
1686 prev_row = row;
1687 suggestion
1688 }))
1689 } else {
1690 None
1691 }
1692 }
1693
1694 fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1695 while row > 0 {
1696 row -= 1;
1697 if !self.is_line_blank(row) {
1698 return Some(row);
1699 }
1700 }
1701 None
1702 }
1703
1704 pub fn chunks<'a, T: ToOffset>(
1705 &'a self,
1706 range: Range<T>,
1707 theme: Option<&'a SyntaxTheme>,
1708 ) -> BufferChunks<'a> {
1709 let range = range.start.to_offset(self)..range.end.to_offset(self);
1710
1711 let mut highlights = None;
1712 let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1713 if let Some(theme) = theme {
1714 for (_, entry) in self.diagnostics_in_range::<_, usize>(range.clone()) {
1715 diagnostic_endpoints.push(DiagnosticEndpoint {
1716 offset: entry.range.start,
1717 is_start: true,
1718 severity: entry.diagnostic.severity,
1719 });
1720 diagnostic_endpoints.push(DiagnosticEndpoint {
1721 offset: entry.range.end,
1722 is_start: false,
1723 severity: entry.diagnostic.severity,
1724 });
1725 }
1726 diagnostic_endpoints
1727 .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1728
1729 if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1730 let mut query_cursor = QueryCursorHandle::new();
1731
1732 // TODO - add a Tree-sitter API to remove the need for this.
1733 let cursor = unsafe {
1734 std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
1735 };
1736 let captures = cursor.set_byte_range(range.clone()).captures(
1737 &grammar.highlights_query,
1738 tree.root_node(),
1739 TextProvider(self.text.as_rope()),
1740 );
1741 highlights = Some(BufferChunkHighlights {
1742 captures,
1743 next_capture: None,
1744 stack: Default::default(),
1745 highlight_map: grammar.highlight_map(),
1746 _query_cursor: query_cursor,
1747 theme,
1748 })
1749 }
1750 }
1751
1752 let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1753 let chunks = self.text.as_rope().chunks_in_range(range.clone());
1754
1755 BufferChunks {
1756 range,
1757 chunks,
1758 diagnostic_endpoints,
1759 error_depth: 0,
1760 warning_depth: 0,
1761 information_depth: 0,
1762 hint_depth: 0,
1763 highlights,
1764 }
1765 }
1766
1767 pub fn language(&self) -> Option<&Arc<Language>> {
1768 self.language.as_ref()
1769 }
1770
1771 fn grammar(&self) -> Option<&Arc<Grammar>> {
1772 self.language
1773 .as_ref()
1774 .and_then(|language| language.grammar.as_ref())
1775 }
1776
1777 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1778 if let Some(tree) = self.tree.as_ref() {
1779 let root = tree.root_node();
1780 let range = range.start.to_offset(self)..range.end.to_offset(self);
1781 let mut node = root.descendant_for_byte_range(range.start, range.end);
1782 while node.map_or(false, |n| n.byte_range() == range) {
1783 node = node.unwrap().parent();
1784 }
1785 node.map(|n| n.byte_range())
1786 } else {
1787 None
1788 }
1789 }
1790
1791 pub fn enclosing_bracket_ranges<T: ToOffset>(
1792 &self,
1793 range: Range<T>,
1794 ) -> Option<(Range<usize>, Range<usize>)> {
1795 let (grammar, tree) = self.grammar().zip(self.tree.as_ref())?;
1796 let open_capture_ix = grammar.brackets_query.capture_index_for_name("open")?;
1797 let close_capture_ix = grammar.brackets_query.capture_index_for_name("close")?;
1798
1799 // Find bracket pairs that *inclusively* contain the given range.
1800 let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
1801 let mut cursor = QueryCursorHandle::new();
1802 let matches = cursor.set_byte_range(range).matches(
1803 &grammar.brackets_query,
1804 tree.root_node(),
1805 TextProvider(self.as_rope()),
1806 );
1807
1808 // Get the ranges of the innermost pair of brackets.
1809 matches
1810 .filter_map(|mat| {
1811 let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
1812 let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
1813 Some((open.byte_range(), close.byte_range()))
1814 })
1815 .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
1816 }
1817
1818 pub fn remote_selections_in_range<'a>(
1819 &'a self,
1820 range: Range<Anchor>,
1821 ) -> impl 'a + Iterator<Item = (ReplicaId, impl 'a + Iterator<Item = &'a Selection<Anchor>>)>
1822 {
1823 self.remote_selections
1824 .iter()
1825 .filter(|(replica_id, set)| {
1826 **replica_id != self.text.replica_id() && !set.selections.is_empty()
1827 })
1828 .map(move |(replica_id, set)| {
1829 let start_ix = match set.selections.binary_search_by(|probe| {
1830 probe
1831 .end
1832 .cmp(&range.start, self)
1833 .unwrap()
1834 .then(Ordering::Greater)
1835 }) {
1836 Ok(ix) | Err(ix) => ix,
1837 };
1838 let end_ix = match set.selections.binary_search_by(|probe| {
1839 probe
1840 .start
1841 .cmp(&range.end, self)
1842 .unwrap()
1843 .then(Ordering::Less)
1844 }) {
1845 Ok(ix) | Err(ix) => ix,
1846 };
1847
1848 (*replica_id, set.selections[start_ix..end_ix].iter())
1849 })
1850 }
1851
1852 pub fn diagnostics_in_range<'a, T, O>(
1853 &'a self,
1854 search_range: Range<T>,
1855 ) -> impl 'a + Iterator<Item = (&'a str, DiagnosticEntry<O>)>
1856 where
1857 T: 'a + Clone + ToOffset,
1858 O: 'a + FromAnchor,
1859 {
1860 self.diagnostic_sets.iter().flat_map(move |set| {
1861 set.range(search_range.clone(), self, true)
1862 .map(|e| (set.provider_name(), e))
1863 })
1864 }
1865
1866 pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
1867 let mut groups = Vec::new();
1868 for set in &self.diagnostic_sets {
1869 set.groups(&mut groups, self);
1870 }
1871 groups
1872 }
1873
1874 pub fn diagnostic_group<'a, O>(
1875 &'a self,
1876 provider_name: &str,
1877 group_id: usize,
1878 ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
1879 where
1880 O: 'a + FromAnchor,
1881 {
1882 self.diagnostic_sets
1883 .iter()
1884 .find(|s| s.provider_name() == provider_name)
1885 .into_iter()
1886 .flat_map(move |s| s.group(group_id, self))
1887 }
1888
1889 pub fn diagnostics_update_count(&self) -> usize {
1890 self.diagnostics_update_count
1891 }
1892
1893 pub fn parse_count(&self) -> usize {
1894 self.parse_count
1895 }
1896
1897 pub fn selections_update_count(&self) -> usize {
1898 self.selections_update_count
1899 }
1900}
1901
1902impl Clone for BufferSnapshot {
1903 fn clone(&self) -> Self {
1904 Self {
1905 text: self.text.clone(),
1906 tree: self.tree.clone(),
1907 remote_selections: self.remote_selections.clone(),
1908 selections_update_count: self.selections_update_count,
1909 diagnostic_sets: self.diagnostic_sets.clone(),
1910 diagnostics_update_count: self.diagnostics_update_count,
1911 is_parsing: self.is_parsing,
1912 language: self.language.clone(),
1913 parse_count: self.parse_count,
1914 }
1915 }
1916}
1917
1918impl Deref for BufferSnapshot {
1919 type Target = text::BufferSnapshot;
1920
1921 fn deref(&self) -> &Self::Target {
1922 &self.text
1923 }
1924}
1925
1926impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
1927 type I = ByteChunks<'a>;
1928
1929 fn text(&mut self, node: tree_sitter::Node) -> Self::I {
1930 ByteChunks(self.0.chunks_in_range(node.byte_range()))
1931 }
1932}
1933
1934struct ByteChunks<'a>(rope::Chunks<'a>);
1935
1936impl<'a> Iterator for ByteChunks<'a> {
1937 type Item = &'a [u8];
1938
1939 fn next(&mut self) -> Option<Self::Item> {
1940 self.0.next().map(str::as_bytes)
1941 }
1942}
1943
1944unsafe impl<'a> Send for BufferChunks<'a> {}
1945
1946impl<'a> BufferChunks<'a> {
1947 pub fn seek(&mut self, offset: usize) {
1948 self.range.start = offset;
1949 self.chunks.seek(self.range.start);
1950 if let Some(highlights) = self.highlights.as_mut() {
1951 highlights
1952 .stack
1953 .retain(|(end_offset, _)| *end_offset > offset);
1954 if let Some((mat, capture_ix)) = &highlights.next_capture {
1955 let capture = mat.captures[*capture_ix as usize];
1956 if offset >= capture.node.start_byte() {
1957 let next_capture_end = capture.node.end_byte();
1958 if offset < next_capture_end {
1959 highlights.stack.push((
1960 next_capture_end,
1961 highlights.highlight_map.get(capture.index),
1962 ));
1963 }
1964 highlights.next_capture.take();
1965 }
1966 }
1967 highlights.captures.set_byte_range(self.range.clone());
1968 }
1969 }
1970
1971 pub fn offset(&self) -> usize {
1972 self.range.start
1973 }
1974
1975 fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
1976 let depth = match endpoint.severity {
1977 DiagnosticSeverity::ERROR => &mut self.error_depth,
1978 DiagnosticSeverity::WARNING => &mut self.warning_depth,
1979 DiagnosticSeverity::INFORMATION => &mut self.information_depth,
1980 DiagnosticSeverity::HINT => &mut self.hint_depth,
1981 _ => return,
1982 };
1983 if endpoint.is_start {
1984 *depth += 1;
1985 } else {
1986 *depth -= 1;
1987 }
1988 }
1989
1990 fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
1991 if self.error_depth > 0 {
1992 Some(DiagnosticSeverity::ERROR)
1993 } else if self.warning_depth > 0 {
1994 Some(DiagnosticSeverity::WARNING)
1995 } else if self.information_depth > 0 {
1996 Some(DiagnosticSeverity::INFORMATION)
1997 } else if self.hint_depth > 0 {
1998 Some(DiagnosticSeverity::HINT)
1999 } else {
2000 None
2001 }
2002 }
2003}
2004
2005impl<'a> Iterator for BufferChunks<'a> {
2006 type Item = Chunk<'a>;
2007
2008 fn next(&mut self) -> Option<Self::Item> {
2009 let mut next_capture_start = usize::MAX;
2010 let mut next_diagnostic_endpoint = usize::MAX;
2011
2012 if let Some(highlights) = self.highlights.as_mut() {
2013 while let Some((parent_capture_end, _)) = highlights.stack.last() {
2014 if *parent_capture_end <= self.range.start {
2015 highlights.stack.pop();
2016 } else {
2017 break;
2018 }
2019 }
2020
2021 if highlights.next_capture.is_none() {
2022 highlights.next_capture = highlights.captures.next();
2023 }
2024
2025 while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
2026 let capture = mat.captures[*capture_ix as usize];
2027 if self.range.start < capture.node.start_byte() {
2028 next_capture_start = capture.node.start_byte();
2029 break;
2030 } else {
2031 let highlight_id = highlights.highlight_map.get(capture.index);
2032 highlights
2033 .stack
2034 .push((capture.node.end_byte(), highlight_id));
2035 highlights.next_capture = highlights.captures.next();
2036 }
2037 }
2038 }
2039
2040 while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
2041 if endpoint.offset <= self.range.start {
2042 self.update_diagnostic_depths(endpoint);
2043 self.diagnostic_endpoints.next();
2044 } else {
2045 next_diagnostic_endpoint = endpoint.offset;
2046 break;
2047 }
2048 }
2049
2050 if let Some(chunk) = self.chunks.peek() {
2051 let chunk_start = self.range.start;
2052 let mut chunk_end = (self.chunks.offset() + chunk.len())
2053 .min(next_capture_start)
2054 .min(next_diagnostic_endpoint);
2055 let mut highlight_style = None;
2056 if let Some(highlights) = self.highlights.as_ref() {
2057 if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
2058 chunk_end = chunk_end.min(*parent_capture_end);
2059 highlight_style = parent_highlight_id.style(highlights.theme);
2060 }
2061 }
2062
2063 let slice =
2064 &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2065 self.range.start = chunk_end;
2066 if self.range.start == self.chunks.offset() + chunk.len() {
2067 self.chunks.next().unwrap();
2068 }
2069
2070 Some(Chunk {
2071 text: slice,
2072 highlight_style,
2073 diagnostic: self.current_diagnostic_severity(),
2074 })
2075 } else {
2076 None
2077 }
2078 }
2079}
2080
2081impl QueryCursorHandle {
2082 fn new() -> Self {
2083 QueryCursorHandle(Some(
2084 QUERY_CURSORS
2085 .lock()
2086 .pop()
2087 .unwrap_or_else(|| QueryCursor::new()),
2088 ))
2089 }
2090}
2091
2092impl Deref for QueryCursorHandle {
2093 type Target = QueryCursor;
2094
2095 fn deref(&self) -> &Self::Target {
2096 self.0.as_ref().unwrap()
2097 }
2098}
2099
2100impl DerefMut for QueryCursorHandle {
2101 fn deref_mut(&mut self) -> &mut Self::Target {
2102 self.0.as_mut().unwrap()
2103 }
2104}
2105
2106impl Drop for QueryCursorHandle {
2107 fn drop(&mut self) {
2108 let mut cursor = self.0.take().unwrap();
2109 cursor.set_byte_range(0..usize::MAX);
2110 cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
2111 QUERY_CURSORS.lock().push(cursor)
2112 }
2113}
2114
2115trait ToTreeSitterPoint {
2116 fn to_ts_point(self) -> tree_sitter::Point;
2117 fn from_ts_point(point: tree_sitter::Point) -> Self;
2118}
2119
2120impl ToTreeSitterPoint for Point {
2121 fn to_ts_point(self) -> tree_sitter::Point {
2122 tree_sitter::Point::new(self.row as usize, self.column as usize)
2123 }
2124
2125 fn from_ts_point(point: tree_sitter::Point) -> Self {
2126 Point::new(point.row as u32, point.column as u32)
2127 }
2128}
2129
2130impl operation_queue::Operation for Operation {
2131 fn lamport_timestamp(&self) -> clock::Lamport {
2132 match self {
2133 Operation::Buffer(_) => {
2134 unreachable!("buffer operations should never be deferred at this layer")
2135 }
2136 Operation::UpdateDiagnostics {
2137 lamport_timestamp, ..
2138 }
2139 | Operation::UpdateSelections {
2140 lamport_timestamp, ..
2141 } => *lamport_timestamp,
2142 }
2143 }
2144}
2145
2146impl Default for Diagnostic {
2147 fn default() -> Self {
2148 Self {
2149 code: Default::default(),
2150 severity: DiagnosticSeverity::ERROR,
2151 message: Default::default(),
2152 group_id: Default::default(),
2153 is_primary: Default::default(),
2154 is_valid: true,
2155 is_disk_based: false,
2156 }
2157 }
2158}
2159
2160pub fn contiguous_ranges(
2161 values: impl Iterator<Item = u32>,
2162 max_len: usize,
2163) -> impl Iterator<Item = Range<u32>> {
2164 let mut values = values.into_iter();
2165 let mut current_range: Option<Range<u32>> = None;
2166 std::iter::from_fn(move || loop {
2167 if let Some(value) = values.next() {
2168 if let Some(range) = &mut current_range {
2169 if value == range.end && range.len() < max_len {
2170 range.end += 1;
2171 continue;
2172 }
2173 }
2174
2175 let prev_range = current_range.clone();
2176 current_range = Some(value..(value + 1));
2177 if prev_range.is_some() {
2178 return prev_range;
2179 }
2180 } else {
2181 return current_range.take();
2182 }
2183 })
2184}