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