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