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