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