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