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