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