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