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