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