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