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