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