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