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