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