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