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