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 #[cfg(test)]
801 pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
802 self.sync_parse_timeout = timeout;
803 }
804
805 /// Called after an edit to synchronize the buffer's main parse tree with
806 /// the buffer's new underlying state.
807 ///
808 /// Locks the syntax map and interpolates the edits since the last reparse
809 /// into the foreground syntax tree.
810 ///
811 /// Then takes a stable snapshot of the syntax map before unlocking it.
812 /// The snapshot with the interpolated edits is sent to a background thread,
813 /// where we ask Tree-sitter to perform an incremental parse.
814 ///
815 /// Meanwhile, in the foreground, we block the main thread for up to 1ms
816 /// waiting on the parse to complete. As soon as it completes, we proceed
817 /// synchronously, unless a 1ms timeout elapses.
818 ///
819 /// If we time out waiting on the parse, we spawn a second task waiting
820 /// until the parse does complete and return with the interpolated tree still
821 /// in the foreground. When the background parse completes, call back into
822 /// the main thread and assign the foreground parse state.
823 ///
824 /// If the buffer or grammar changed since the start of the background parse,
825 /// initiate an additional reparse recursively. To avoid concurrent parses
826 /// for the same buffer, we only initiate a new parse if we are not already
827 /// parsing in the background.
828 fn reparse(&mut self, cx: &mut ModelContext<Self>) {
829 if self.parsing_in_background {
830 return;
831 }
832 let language = if let Some(language) = self.language.clone() {
833 language
834 } else {
835 return;
836 };
837
838 let text = self.text_snapshot();
839 let parsed_version = self.version();
840
841 let mut syntax_map = self.syntax_map.lock();
842 syntax_map.interpolate(&text);
843 let language_registry = syntax_map.language_registry();
844 let mut syntax_snapshot = syntax_map.snapshot();
845 let syntax_map_version = syntax_map.parsed_version();
846 drop(syntax_map);
847
848 let parse_task = cx.background().spawn({
849 let language = language.clone();
850 async move {
851 syntax_snapshot.reparse(&syntax_map_version, &text, language_registry, language);
852 syntax_snapshot
853 }
854 });
855
856 match cx
857 .background()
858 .block_with_timeout(self.sync_parse_timeout, parse_task)
859 {
860 Ok(new_syntax_snapshot) => {
861 self.did_finish_parsing(new_syntax_snapshot, parsed_version, cx);
862 return;
863 }
864 Err(parse_task) => {
865 self.parsing_in_background = true;
866 cx.spawn(move |this, mut cx| async move {
867 let new_syntax_map = parse_task.await;
868 this.update(&mut cx, move |this, cx| {
869 let grammar_changed =
870 this.language.as_ref().map_or(true, |current_language| {
871 !Arc::ptr_eq(&language, current_language)
872 });
873 let parse_again =
874 this.version.changed_since(&parsed_version) || grammar_changed;
875 this.did_finish_parsing(new_syntax_map, parsed_version, cx);
876 this.parsing_in_background = false;
877 if parse_again {
878 this.reparse(cx);
879 }
880 });
881 })
882 .detach();
883 }
884 }
885 }
886
887 fn did_finish_parsing(
888 &mut self,
889 syntax_snapshot: SyntaxSnapshot,
890 version: clock::Global,
891 cx: &mut ModelContext<Self>,
892 ) {
893 self.parse_count += 1;
894 self.syntax_map.lock().did_parse(syntax_snapshot, version);
895 self.request_autoindent(cx);
896 cx.emit(Event::Reparsed);
897 cx.notify();
898 }
899
900 pub fn update_diagnostics(&mut self, diagnostics: DiagnosticSet, cx: &mut ModelContext<Self>) {
901 let lamport_timestamp = self.text.lamport_clock.tick();
902 let op = Operation::UpdateDiagnostics {
903 diagnostics: diagnostics.iter().cloned().collect(),
904 lamport_timestamp,
905 };
906 self.apply_diagnostic_update(diagnostics, lamport_timestamp, cx);
907 self.send_operation(op, cx);
908 }
909
910 fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
911 if let Some(indent_sizes) = self.compute_autoindents() {
912 let indent_sizes = cx.background().spawn(indent_sizes);
913 match cx
914 .background()
915 .block_with_timeout(Duration::from_micros(500), indent_sizes)
916 {
917 Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
918 Err(indent_sizes) => {
919 self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
920 let indent_sizes = indent_sizes.await;
921 this.update(&mut cx, |this, cx| {
922 this.apply_autoindents(indent_sizes, cx);
923 });
924 }));
925 }
926 }
927 } else {
928 self.autoindent_requests.clear();
929 }
930 }
931
932 fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>>> {
933 let max_rows_between_yields = 100;
934 let snapshot = self.snapshot();
935 if snapshot.syntax.is_empty() || self.autoindent_requests.is_empty() {
936 return None;
937 }
938
939 let autoindent_requests = self.autoindent_requests.clone();
940 Some(async move {
941 let mut indent_sizes = BTreeMap::new();
942 for request in autoindent_requests {
943 // Resolve each edited range to its row in the current buffer and in the
944 // buffer before this batch of edits.
945 let mut row_ranges = Vec::new();
946 let mut old_to_new_rows = BTreeMap::new();
947 let mut language_indent_sizes_by_new_row = Vec::new();
948 for entry in &request.entries {
949 let position = entry.range.start;
950 let new_row = position.to_point(&snapshot).row;
951 let new_end_row = entry.range.end.to_point(&snapshot).row + 1;
952 language_indent_sizes_by_new_row.push((new_row, entry.indent_size));
953
954 if !entry.first_line_is_new {
955 let old_row = position.to_point(&request.before_edit).row;
956 old_to_new_rows.insert(old_row, new_row);
957 }
958 row_ranges.push((new_row..new_end_row, entry.original_indent_column));
959 }
960
961 // Build a map containing the suggested indentation for each of the edited lines
962 // with respect to the state of the buffer before these edits. This map is keyed
963 // by the rows for these lines in the current state of the buffer.
964 let mut old_suggestions = BTreeMap::<u32, (IndentSize, bool)>::default();
965 let old_edited_ranges =
966 contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
967 let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
968 let mut language_indent_size = IndentSize::default();
969 for old_edited_range in old_edited_ranges {
970 let suggestions = request
971 .before_edit
972 .suggest_autoindents(old_edited_range.clone())
973 .into_iter()
974 .flatten();
975 for (old_row, suggestion) in old_edited_range.zip(suggestions) {
976 if let Some(suggestion) = suggestion {
977 let new_row = *old_to_new_rows.get(&old_row).unwrap();
978
979 // Find the indent size based on the language for this row.
980 while let Some((row, size)) = language_indent_sizes.peek() {
981 if *row > new_row {
982 break;
983 }
984 language_indent_size = *size;
985 language_indent_sizes.next();
986 }
987
988 let suggested_indent = old_to_new_rows
989 .get(&suggestion.basis_row)
990 .and_then(|from_row| {
991 Some(old_suggestions.get(from_row).copied()?.0)
992 })
993 .unwrap_or_else(|| {
994 request
995 .before_edit
996 .indent_size_for_line(suggestion.basis_row)
997 })
998 .with_delta(suggestion.delta, language_indent_size);
999 old_suggestions
1000 .insert(new_row, (suggested_indent, suggestion.within_error));
1001 }
1002 }
1003 yield_now().await;
1004 }
1005
1006 // In block mode, only compute indentation suggestions for the first line
1007 // of each insertion. Otherwise, compute suggestions for every inserted line.
1008 let new_edited_row_ranges = contiguous_ranges(
1009 row_ranges.iter().flat_map(|(range, _)| {
1010 if request.is_block_mode {
1011 range.start..range.start + 1
1012 } else {
1013 range.clone()
1014 }
1015 }),
1016 max_rows_between_yields,
1017 );
1018
1019 // Compute new suggestions for each line, but only include them in the result
1020 // if they differ from the old suggestion for that line.
1021 let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1022 let mut language_indent_size = IndentSize::default();
1023 for new_edited_row_range in new_edited_row_ranges {
1024 let suggestions = snapshot
1025 .suggest_autoindents(new_edited_row_range.clone())
1026 .into_iter()
1027 .flatten();
1028 for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
1029 if let Some(suggestion) = suggestion {
1030 // Find the indent size based on the language for this row.
1031 while let Some((row, size)) = language_indent_sizes.peek() {
1032 if *row > new_row {
1033 break;
1034 }
1035 language_indent_size = *size;
1036 language_indent_sizes.next();
1037 }
1038
1039 let suggested_indent = indent_sizes
1040 .get(&suggestion.basis_row)
1041 .copied()
1042 .unwrap_or_else(|| {
1043 snapshot.indent_size_for_line(suggestion.basis_row)
1044 })
1045 .with_delta(suggestion.delta, language_indent_size);
1046 if old_suggestions.get(&new_row).map_or(
1047 true,
1048 |(old_indentation, was_within_error)| {
1049 suggested_indent != *old_indentation
1050 && (!suggestion.within_error || *was_within_error)
1051 },
1052 ) {
1053 indent_sizes.insert(new_row, suggested_indent);
1054 }
1055 }
1056 }
1057 yield_now().await;
1058 }
1059
1060 // For each block of inserted text, adjust the indentation of the remaining
1061 // lines of the block by the same amount as the first line was adjusted.
1062 if request.is_block_mode {
1063 for (row_range, original_indent_column) in
1064 row_ranges
1065 .into_iter()
1066 .filter_map(|(range, original_indent_column)| {
1067 if range.len() > 1 {
1068 Some((range, original_indent_column?))
1069 } else {
1070 None
1071 }
1072 })
1073 {
1074 let new_indent = indent_sizes
1075 .get(&row_range.start)
1076 .copied()
1077 .unwrap_or_else(|| snapshot.indent_size_for_line(row_range.start));
1078 let delta = new_indent.len as i64 - original_indent_column as i64;
1079 if delta != 0 {
1080 for row in row_range.skip(1) {
1081 indent_sizes.entry(row).or_insert_with(|| {
1082 let mut size = snapshot.indent_size_for_line(row);
1083 if size.kind == new_indent.kind {
1084 match delta.cmp(&0) {
1085 Ordering::Greater => size.len += delta as u32,
1086 Ordering::Less => {
1087 size.len = size.len.saturating_sub(-delta as u32)
1088 }
1089 Ordering::Equal => {}
1090 }
1091 }
1092 size
1093 });
1094 }
1095 }
1096 }
1097 }
1098 }
1099
1100 indent_sizes
1101 })
1102 }
1103
1104 fn apply_autoindents(
1105 &mut self,
1106 indent_sizes: BTreeMap<u32, IndentSize>,
1107 cx: &mut ModelContext<Self>,
1108 ) {
1109 self.autoindent_requests.clear();
1110
1111 let edits: Vec<_> = indent_sizes
1112 .into_iter()
1113 .filter_map(|(row, indent_size)| {
1114 let current_size = indent_size_for_line(self, row);
1115 Self::edit_for_indent_size_adjustment(row, current_size, indent_size)
1116 })
1117 .collect();
1118
1119 self.edit(edits, None, cx);
1120 }
1121
1122 // Create a minimal edit that will cause the the given row to be indented
1123 // with the given size. After applying this edit, the length of the line
1124 // will always be at least `new_size.len`.
1125 pub fn edit_for_indent_size_adjustment(
1126 row: u32,
1127 current_size: IndentSize,
1128 new_size: IndentSize,
1129 ) -> Option<(Range<Point>, String)> {
1130 if new_size.kind != current_size.kind {
1131 Some((
1132 Point::new(row, 0)..Point::new(row, current_size.len),
1133 iter::repeat(new_size.char())
1134 .take(new_size.len as usize)
1135 .collect::<String>(),
1136 ))
1137 } else {
1138 match new_size.len.cmp(¤t_size.len) {
1139 Ordering::Greater => {
1140 let point = Point::new(row, 0);
1141 Some((
1142 point..point,
1143 iter::repeat(new_size.char())
1144 .take((new_size.len - current_size.len) as usize)
1145 .collect::<String>(),
1146 ))
1147 }
1148
1149 Ordering::Less => Some((
1150 Point::new(row, 0)..Point::new(row, current_size.len - new_size.len),
1151 String::new(),
1152 )),
1153
1154 Ordering::Equal => None,
1155 }
1156 }
1157 }
1158
1159 pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
1160 let old_text = self.as_rope().clone();
1161 let base_version = self.version();
1162 cx.background().spawn(async move {
1163 let old_text = old_text.to_string();
1164 let line_ending = LineEnding::detect(&new_text);
1165 LineEnding::normalize(&mut new_text);
1166 let diff = TextDiff::from_chars(old_text.as_str(), new_text.as_str());
1167 let mut edits = Vec::new();
1168 let mut offset = 0;
1169 let empty: Arc<str> = "".into();
1170 for change in diff.iter_all_changes() {
1171 let value = change.value();
1172 let end_offset = offset + value.len();
1173 match change.tag() {
1174 ChangeTag::Equal => {
1175 offset = end_offset;
1176 }
1177 ChangeTag::Delete => {
1178 edits.push((offset..end_offset, empty.clone()));
1179 offset = end_offset;
1180 }
1181 ChangeTag::Insert => {
1182 edits.push((offset..offset, value.into()));
1183 }
1184 }
1185 }
1186 Diff {
1187 base_version,
1188 line_ending,
1189 edits,
1190 }
1191 })
1192 }
1193
1194 pub fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> Option<&Transaction> {
1195 if self.version == diff.base_version {
1196 self.finalize_last_transaction();
1197 self.start_transaction();
1198 self.text.set_line_ending(diff.line_ending);
1199 self.edit(diff.edits, None, cx);
1200 if self.end_transaction(cx).is_some() {
1201 self.finalize_last_transaction()
1202 } else {
1203 None
1204 }
1205 } else {
1206 None
1207 }
1208 }
1209
1210 pub fn is_dirty(&self) -> bool {
1211 self.saved_version_fingerprint != self.as_rope().fingerprint()
1212 || self.file.as_ref().map_or(false, |file| file.is_deleted())
1213 }
1214
1215 pub fn has_conflict(&self) -> bool {
1216 self.saved_version_fingerprint != self.as_rope().fingerprint()
1217 && self
1218 .file
1219 .as_ref()
1220 .map_or(false, |file| file.mtime() > self.saved_mtime)
1221 }
1222
1223 pub fn subscribe(&mut self) -> Subscription {
1224 self.text.subscribe()
1225 }
1226
1227 pub fn start_transaction(&mut self) -> Option<TransactionId> {
1228 self.start_transaction_at(Instant::now())
1229 }
1230
1231 pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1232 self.transaction_depth += 1;
1233 if self.was_dirty_before_starting_transaction.is_none() {
1234 self.was_dirty_before_starting_transaction = Some(self.is_dirty());
1235 }
1236 self.text.start_transaction_at(now)
1237 }
1238
1239 pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1240 self.end_transaction_at(Instant::now(), cx)
1241 }
1242
1243 pub fn end_transaction_at(
1244 &mut self,
1245 now: Instant,
1246 cx: &mut ModelContext<Self>,
1247 ) -> Option<TransactionId> {
1248 assert!(self.transaction_depth > 0);
1249 self.transaction_depth -= 1;
1250 let was_dirty = if self.transaction_depth == 0 {
1251 self.was_dirty_before_starting_transaction.take().unwrap()
1252 } else {
1253 false
1254 };
1255 if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1256 self.did_edit(&start_version, was_dirty, cx);
1257 Some(transaction_id)
1258 } else {
1259 None
1260 }
1261 }
1262
1263 pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1264 self.text.push_transaction(transaction, now);
1265 }
1266
1267 pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1268 self.text.finalize_last_transaction()
1269 }
1270
1271 pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
1272 self.text.group_until_transaction(transaction_id);
1273 }
1274
1275 pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1276 self.text.forget_transaction(transaction_id);
1277 }
1278
1279 pub fn wait_for_edits(
1280 &mut self,
1281 edit_ids: impl IntoIterator<Item = clock::Local>,
1282 ) -> impl Future<Output = ()> {
1283 self.text.wait_for_edits(edit_ids)
1284 }
1285
1286 pub fn wait_for_anchors<'a>(
1287 &mut self,
1288 anchors: impl IntoIterator<Item = &'a Anchor>,
1289 ) -> impl Future<Output = ()> {
1290 self.text.wait_for_anchors(anchors)
1291 }
1292
1293 pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = ()> {
1294 self.text.wait_for_version(version)
1295 }
1296
1297 pub fn set_active_selections(
1298 &mut self,
1299 selections: Arc<[Selection<Anchor>]>,
1300 line_mode: bool,
1301 cursor_shape: CursorShape,
1302 cx: &mut ModelContext<Self>,
1303 ) {
1304 let lamport_timestamp = self.text.lamport_clock.tick();
1305 self.remote_selections.insert(
1306 self.text.replica_id(),
1307 SelectionSet {
1308 selections: selections.clone(),
1309 lamport_timestamp,
1310 line_mode,
1311 cursor_shape,
1312 },
1313 );
1314 self.send_operation(
1315 Operation::UpdateSelections {
1316 selections,
1317 line_mode,
1318 lamport_timestamp,
1319 cursor_shape,
1320 },
1321 cx,
1322 );
1323 }
1324
1325 pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1326 self.set_active_selections(Arc::from([]), false, Default::default(), cx);
1327 }
1328
1329 pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Local>
1330 where
1331 T: Into<Arc<str>>,
1332 {
1333 self.edit([(0..self.len(), text)], None, cx)
1334 }
1335
1336 pub fn edit<I, S, T>(
1337 &mut self,
1338 edits_iter: I,
1339 autoindent_mode: Option<AutoindentMode>,
1340 cx: &mut ModelContext<Self>,
1341 ) -> Option<clock::Local>
1342 where
1343 I: IntoIterator<Item = (Range<S>, T)>,
1344 S: ToOffset,
1345 T: Into<Arc<str>>,
1346 {
1347 // Skip invalid edits and coalesce contiguous ones.
1348 let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1349 for (range, new_text) in edits_iter {
1350 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1351 if range.start > range.end {
1352 mem::swap(&mut range.start, &mut range.end);
1353 }
1354 let new_text = new_text.into();
1355 if !new_text.is_empty() || !range.is_empty() {
1356 if let Some((prev_range, prev_text)) = edits.last_mut() {
1357 if prev_range.end >= range.start {
1358 prev_range.end = cmp::max(prev_range.end, range.end);
1359 *prev_text = format!("{prev_text}{new_text}").into();
1360 } else {
1361 edits.push((range, new_text));
1362 }
1363 } else {
1364 edits.push((range, new_text));
1365 }
1366 }
1367 }
1368 if edits.is_empty() {
1369 return None;
1370 }
1371
1372 self.start_transaction();
1373 self.pending_autoindent.take();
1374 let autoindent_request = autoindent_mode
1375 .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
1376
1377 let edit_operation = self.text.edit(edits.iter().cloned());
1378 let edit_id = edit_operation.local_timestamp();
1379
1380 if let Some((before_edit, mode)) = autoindent_request {
1381 let mut delta = 0isize;
1382 let entries = edits
1383 .into_iter()
1384 .enumerate()
1385 .zip(&edit_operation.as_edit().unwrap().new_text)
1386 .map(|((ix, (range, _)), new_text)| {
1387 let new_text_len = new_text.len();
1388 let old_start = range.start.to_point(&before_edit);
1389 let new_start = (delta + range.start as isize) as usize;
1390 delta += new_text_len as isize - (range.end as isize - range.start as isize);
1391
1392 let mut range_of_insertion_to_indent = 0..new_text_len;
1393 let mut first_line_is_new = false;
1394 let mut original_indent_column = None;
1395
1396 // When inserting an entire line at the beginning of an existing line,
1397 // treat the insertion as new.
1398 if new_text.contains('\n')
1399 && old_start.column <= before_edit.indent_size_for_line(old_start.row).len
1400 {
1401 first_line_is_new = true;
1402 }
1403
1404 // When inserting text starting with a newline, avoid auto-indenting the
1405 // previous line.
1406 if new_text.starts_with('\n') {
1407 range_of_insertion_to_indent.start += 1;
1408 first_line_is_new = true;
1409 }
1410
1411 // Avoid auto-indenting after the insertion.
1412 if let AutoindentMode::Block {
1413 original_indent_columns,
1414 } = &mode
1415 {
1416 original_indent_column =
1417 Some(original_indent_columns.get(ix).copied().unwrap_or_else(|| {
1418 indent_size_for_text(
1419 new_text[range_of_insertion_to_indent.clone()].chars(),
1420 )
1421 .len
1422 }));
1423 if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
1424 range_of_insertion_to_indent.end -= 1;
1425 }
1426 }
1427
1428 AutoindentRequestEntry {
1429 first_line_is_new,
1430 original_indent_column,
1431 indent_size: before_edit.language_indent_size_at(range.start, cx),
1432 range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
1433 ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
1434 }
1435 })
1436 .collect();
1437
1438 self.autoindent_requests.push(Arc::new(AutoindentRequest {
1439 before_edit,
1440 entries,
1441 is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
1442 }));
1443 }
1444
1445 self.end_transaction(cx);
1446 self.send_operation(Operation::Buffer(edit_operation), cx);
1447 Some(edit_id)
1448 }
1449
1450 fn did_edit(
1451 &mut self,
1452 old_version: &clock::Global,
1453 was_dirty: bool,
1454 cx: &mut ModelContext<Self>,
1455 ) {
1456 if self.edits_since::<usize>(old_version).next().is_none() {
1457 return;
1458 }
1459
1460 self.reparse(cx);
1461
1462 cx.emit(Event::Edited);
1463 if was_dirty != self.is_dirty() {
1464 cx.emit(Event::DirtyChanged);
1465 }
1466 cx.notify();
1467 }
1468
1469 pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1470 &mut self,
1471 ops: I,
1472 cx: &mut ModelContext<Self>,
1473 ) -> Result<()> {
1474 self.pending_autoindent.take();
1475 let was_dirty = self.is_dirty();
1476 let old_version = self.version.clone();
1477 let mut deferred_ops = Vec::new();
1478 let buffer_ops = ops
1479 .into_iter()
1480 .filter_map(|op| match op {
1481 Operation::Buffer(op) => Some(op),
1482 _ => {
1483 if self.can_apply_op(&op) {
1484 self.apply_op(op, cx);
1485 } else {
1486 deferred_ops.push(op);
1487 }
1488 None
1489 }
1490 })
1491 .collect::<Vec<_>>();
1492 self.text.apply_ops(buffer_ops)?;
1493 self.deferred_ops.insert(deferred_ops);
1494 self.flush_deferred_ops(cx);
1495 self.did_edit(&old_version, was_dirty, cx);
1496 // Notify independently of whether the buffer was edited as the operations could include a
1497 // selection update.
1498 cx.notify();
1499 Ok(())
1500 }
1501
1502 fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1503 let mut deferred_ops = Vec::new();
1504 for op in self.deferred_ops.drain().iter().cloned() {
1505 if self.can_apply_op(&op) {
1506 self.apply_op(op, cx);
1507 } else {
1508 deferred_ops.push(op);
1509 }
1510 }
1511 self.deferred_ops.insert(deferred_ops);
1512 }
1513
1514 fn can_apply_op(&self, operation: &Operation) -> bool {
1515 match operation {
1516 Operation::Buffer(_) => {
1517 unreachable!("buffer operations should never be applied at this layer")
1518 }
1519 Operation::UpdateDiagnostics {
1520 diagnostics: diagnostic_set,
1521 ..
1522 } => diagnostic_set.iter().all(|diagnostic| {
1523 self.text.can_resolve(&diagnostic.range.start)
1524 && self.text.can_resolve(&diagnostic.range.end)
1525 }),
1526 Operation::UpdateSelections { selections, .. } => selections
1527 .iter()
1528 .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1529 Operation::UpdateCompletionTriggers { .. } => true,
1530 }
1531 }
1532
1533 fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1534 match operation {
1535 Operation::Buffer(_) => {
1536 unreachable!("buffer operations should never be applied at this layer")
1537 }
1538 Operation::UpdateDiagnostics {
1539 diagnostics: diagnostic_set,
1540 lamport_timestamp,
1541 } => {
1542 let snapshot = self.snapshot();
1543 self.apply_diagnostic_update(
1544 DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1545 lamport_timestamp,
1546 cx,
1547 );
1548 }
1549 Operation::UpdateSelections {
1550 selections,
1551 lamport_timestamp,
1552 line_mode,
1553 cursor_shape,
1554 } => {
1555 if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
1556 if set.lamport_timestamp > lamport_timestamp {
1557 return;
1558 }
1559 }
1560
1561 self.remote_selections.insert(
1562 lamport_timestamp.replica_id,
1563 SelectionSet {
1564 selections,
1565 lamport_timestamp,
1566 line_mode,
1567 cursor_shape,
1568 },
1569 );
1570 self.text.lamport_clock.observe(lamport_timestamp);
1571 self.selections_update_count += 1;
1572 }
1573 Operation::UpdateCompletionTriggers {
1574 triggers,
1575 lamport_timestamp,
1576 } => {
1577 self.completion_triggers = triggers;
1578 self.text.lamport_clock.observe(lamport_timestamp);
1579 }
1580 }
1581 }
1582
1583 fn apply_diagnostic_update(
1584 &mut self,
1585 diagnostics: DiagnosticSet,
1586 lamport_timestamp: clock::Lamport,
1587 cx: &mut ModelContext<Self>,
1588 ) {
1589 if lamport_timestamp > self.diagnostics_timestamp {
1590 self.diagnostics = diagnostics;
1591 self.diagnostics_timestamp = lamport_timestamp;
1592 self.diagnostics_update_count += 1;
1593 self.text.lamport_clock.observe(lamport_timestamp);
1594 cx.notify();
1595 cx.emit(Event::DiagnosticsUpdated);
1596 }
1597 }
1598
1599 fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1600 cx.emit(Event::Operation(operation));
1601 }
1602
1603 pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1604 self.remote_selections.remove(&replica_id);
1605 cx.notify();
1606 }
1607
1608 pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1609 let was_dirty = self.is_dirty();
1610 let old_version = self.version.clone();
1611
1612 if let Some((transaction_id, operation)) = self.text.undo() {
1613 self.send_operation(Operation::Buffer(operation), cx);
1614 self.did_edit(&old_version, was_dirty, cx);
1615 Some(transaction_id)
1616 } else {
1617 None
1618 }
1619 }
1620
1621 pub fn undo_to_transaction(
1622 &mut self,
1623 transaction_id: TransactionId,
1624 cx: &mut ModelContext<Self>,
1625 ) -> bool {
1626 let was_dirty = self.is_dirty();
1627 let old_version = self.version.clone();
1628
1629 let operations = self.text.undo_to_transaction(transaction_id);
1630 let undone = !operations.is_empty();
1631 for operation in operations {
1632 self.send_operation(Operation::Buffer(operation), cx);
1633 }
1634 if undone {
1635 self.did_edit(&old_version, was_dirty, cx)
1636 }
1637 undone
1638 }
1639
1640 pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1641 let was_dirty = self.is_dirty();
1642 let old_version = self.version.clone();
1643
1644 if let Some((transaction_id, operation)) = self.text.redo() {
1645 self.send_operation(Operation::Buffer(operation), cx);
1646 self.did_edit(&old_version, was_dirty, cx);
1647 Some(transaction_id)
1648 } else {
1649 None
1650 }
1651 }
1652
1653 pub fn redo_to_transaction(
1654 &mut self,
1655 transaction_id: TransactionId,
1656 cx: &mut ModelContext<Self>,
1657 ) -> bool {
1658 let was_dirty = self.is_dirty();
1659 let old_version = self.version.clone();
1660
1661 let operations = self.text.redo_to_transaction(transaction_id);
1662 let redone = !operations.is_empty();
1663 for operation in operations {
1664 self.send_operation(Operation::Buffer(operation), cx);
1665 }
1666 if redone {
1667 self.did_edit(&old_version, was_dirty, cx)
1668 }
1669 redone
1670 }
1671
1672 pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
1673 self.completion_triggers = triggers.clone();
1674 self.completion_triggers_timestamp = self.text.lamport_clock.tick();
1675 self.send_operation(
1676 Operation::UpdateCompletionTriggers {
1677 triggers,
1678 lamport_timestamp: self.completion_triggers_timestamp,
1679 },
1680 cx,
1681 );
1682 cx.notify();
1683 }
1684
1685 pub fn completion_triggers(&self) -> &[String] {
1686 &self.completion_triggers
1687 }
1688}
1689
1690#[cfg(any(test, feature = "test-support"))]
1691impl Buffer {
1692 pub fn edit_via_marked_text(
1693 &mut self,
1694 marked_string: &str,
1695 autoindent_mode: Option<AutoindentMode>,
1696 cx: &mut ModelContext<Self>,
1697 ) {
1698 let edits = self.edits_for_marked_text(marked_string);
1699 self.edit(edits, autoindent_mode, cx);
1700 }
1701
1702 pub fn set_group_interval(&mut self, group_interval: Duration) {
1703 self.text.set_group_interval(group_interval);
1704 }
1705
1706 pub fn randomly_edit<T>(
1707 &mut self,
1708 rng: &mut T,
1709 old_range_count: usize,
1710 cx: &mut ModelContext<Self>,
1711 ) where
1712 T: rand::Rng,
1713 {
1714 let mut edits: Vec<(Range<usize>, String)> = Vec::new();
1715 let mut last_end = None;
1716 for _ in 0..old_range_count {
1717 if last_end.map_or(false, |last_end| last_end >= self.len()) {
1718 break;
1719 }
1720
1721 let new_start = last_end.map_or(0, |last_end| last_end + 1);
1722 let mut range = self.random_byte_range(new_start, rng);
1723 if rng.gen_bool(0.2) {
1724 mem::swap(&mut range.start, &mut range.end);
1725 }
1726 last_end = Some(range.end);
1727
1728 let new_text_len = rng.gen_range(0..10);
1729 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1730
1731 edits.push((range, new_text));
1732 }
1733 log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
1734 self.edit(edits, None, cx);
1735 }
1736
1737 pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1738 let was_dirty = self.is_dirty();
1739 let old_version = self.version.clone();
1740
1741 let ops = self.text.randomly_undo_redo(rng);
1742 if !ops.is_empty() {
1743 for op in ops {
1744 self.send_operation(Operation::Buffer(op), cx);
1745 self.did_edit(&old_version, was_dirty, cx);
1746 }
1747 }
1748 }
1749}
1750
1751impl Entity for Buffer {
1752 type Event = Event;
1753}
1754
1755impl Deref for Buffer {
1756 type Target = TextBuffer;
1757
1758 fn deref(&self) -> &Self::Target {
1759 &self.text
1760 }
1761}
1762
1763impl BufferSnapshot {
1764 pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
1765 indent_size_for_line(self, row)
1766 }
1767
1768 pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &AppContext) -> IndentSize {
1769 let language_name = self.language_at(position).map(|language| language.name());
1770 let settings = cx.global::<Settings>();
1771 if settings.hard_tabs(language_name.as_deref()) {
1772 IndentSize::tab()
1773 } else {
1774 IndentSize::spaces(settings.tab_size(language_name.as_deref()).get())
1775 }
1776 }
1777
1778 pub fn suggested_indents(
1779 &self,
1780 rows: impl Iterator<Item = u32>,
1781 single_indent_size: IndentSize,
1782 ) -> BTreeMap<u32, IndentSize> {
1783 let mut result = BTreeMap::new();
1784
1785 for row_range in contiguous_ranges(rows, 10) {
1786 let suggestions = match self.suggest_autoindents(row_range.clone()) {
1787 Some(suggestions) => suggestions,
1788 _ => break,
1789 };
1790
1791 for (row, suggestion) in row_range.zip(suggestions) {
1792 let indent_size = if let Some(suggestion) = suggestion {
1793 result
1794 .get(&suggestion.basis_row)
1795 .copied()
1796 .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
1797 .with_delta(suggestion.delta, single_indent_size)
1798 } else {
1799 self.indent_size_for_line(row)
1800 };
1801
1802 result.insert(row, indent_size);
1803 }
1804 }
1805
1806 result
1807 }
1808
1809 fn suggest_autoindents(
1810 &self,
1811 row_range: Range<u32>,
1812 ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
1813 let config = &self.language.as_ref()?.config;
1814 let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1815
1816 // Find the suggested indentation ranges based on the syntax tree.
1817 let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
1818 let end = Point::new(row_range.end, 0);
1819 let range = (start..end).to_offset(&self.text);
1820 let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
1821 Some(&grammar.indents_config.as_ref()?.query)
1822 });
1823 let indent_configs = matches
1824 .grammars()
1825 .iter()
1826 .map(|grammar| grammar.indents_config.as_ref().unwrap())
1827 .collect::<Vec<_>>();
1828
1829 let mut indent_ranges = Vec::<Range<Point>>::new();
1830 let mut outdent_positions = Vec::<Point>::new();
1831 while let Some(mat) = matches.peek() {
1832 let mut start: Option<Point> = None;
1833 let mut end: Option<Point> = None;
1834
1835 let config = &indent_configs[mat.grammar_index];
1836 for capture in mat.captures {
1837 if capture.index == config.indent_capture_ix {
1838 start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1839 end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1840 } else if Some(capture.index) == config.start_capture_ix {
1841 start = Some(Point::from_ts_point(capture.node.end_position()));
1842 } else if Some(capture.index) == config.end_capture_ix {
1843 end = Some(Point::from_ts_point(capture.node.start_position()));
1844 } else if Some(capture.index) == config.outdent_capture_ix {
1845 outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
1846 }
1847 }
1848
1849 matches.advance();
1850 if let Some((start, end)) = start.zip(end) {
1851 if start.row == end.row {
1852 continue;
1853 }
1854
1855 let range = start..end;
1856 match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
1857 Err(ix) => indent_ranges.insert(ix, range),
1858 Ok(ix) => {
1859 let prev_range = &mut indent_ranges[ix];
1860 prev_range.end = prev_range.end.max(range.end);
1861 }
1862 }
1863 }
1864 }
1865
1866 let mut error_ranges = Vec::<Range<Point>>::new();
1867 let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
1868 Some(&grammar.error_query)
1869 });
1870 while let Some(mat) = matches.peek() {
1871 let node = mat.captures[0].node;
1872 let start = Point::from_ts_point(node.start_position());
1873 let end = Point::from_ts_point(node.end_position());
1874 let range = start..end;
1875 let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
1876 Ok(ix) | Err(ix) => ix,
1877 };
1878 let mut end_ix = ix;
1879 while let Some(existing_range) = error_ranges.get(end_ix) {
1880 if existing_range.end < end {
1881 end_ix += 1;
1882 } else {
1883 break;
1884 }
1885 }
1886 error_ranges.splice(ix..end_ix, [range]);
1887 matches.advance();
1888 }
1889
1890 outdent_positions.sort();
1891 for outdent_position in outdent_positions {
1892 // find the innermost indent range containing this outdent_position
1893 // set its end to the outdent position
1894 if let Some(range_to_truncate) = indent_ranges
1895 .iter_mut()
1896 .filter(|indent_range| indent_range.contains(&outdent_position))
1897 .last()
1898 {
1899 range_to_truncate.end = outdent_position;
1900 }
1901 }
1902
1903 // Find the suggested indentation increases and decreased based on regexes.
1904 let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
1905 self.for_each_line(
1906 Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
1907 ..Point::new(row_range.end, 0),
1908 |row, line| {
1909 if config
1910 .decrease_indent_pattern
1911 .as_ref()
1912 .map_or(false, |regex| regex.is_match(line))
1913 {
1914 indent_change_rows.push((row, Ordering::Less));
1915 }
1916 if config
1917 .increase_indent_pattern
1918 .as_ref()
1919 .map_or(false, |regex| regex.is_match(line))
1920 {
1921 indent_change_rows.push((row + 1, Ordering::Greater));
1922 }
1923 },
1924 );
1925
1926 let mut indent_changes = indent_change_rows.into_iter().peekable();
1927 let mut prev_row = if config.auto_indent_using_last_non_empty_line {
1928 prev_non_blank_row.unwrap_or(0)
1929 } else {
1930 row_range.start.saturating_sub(1)
1931 };
1932 let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
1933 Some(row_range.map(move |row| {
1934 let row_start = Point::new(row, self.indent_size_for_line(row).len);
1935
1936 let mut indent_from_prev_row = false;
1937 let mut outdent_from_prev_row = false;
1938 let mut outdent_to_row = u32::MAX;
1939
1940 while let Some((indent_row, delta)) = indent_changes.peek() {
1941 match indent_row.cmp(&row) {
1942 Ordering::Equal => match delta {
1943 Ordering::Less => outdent_from_prev_row = true,
1944 Ordering::Greater => indent_from_prev_row = true,
1945 _ => {}
1946 },
1947
1948 Ordering::Greater => break,
1949 Ordering::Less => {}
1950 }
1951
1952 indent_changes.next();
1953 }
1954
1955 for range in &indent_ranges {
1956 if range.start.row >= row {
1957 break;
1958 }
1959 if range.start.row == prev_row && range.end > row_start {
1960 indent_from_prev_row = true;
1961 }
1962 if range.end > prev_row_start && range.end <= row_start {
1963 outdent_to_row = outdent_to_row.min(range.start.row);
1964 }
1965 }
1966
1967 let within_error = error_ranges
1968 .iter()
1969 .any(|e| e.start.row < row && e.end > row_start);
1970
1971 let suggestion = if outdent_to_row == prev_row
1972 || (outdent_from_prev_row && indent_from_prev_row)
1973 {
1974 Some(IndentSuggestion {
1975 basis_row: prev_row,
1976 delta: Ordering::Equal,
1977 within_error,
1978 })
1979 } else if indent_from_prev_row {
1980 Some(IndentSuggestion {
1981 basis_row: prev_row,
1982 delta: Ordering::Greater,
1983 within_error,
1984 })
1985 } else if outdent_to_row < prev_row {
1986 Some(IndentSuggestion {
1987 basis_row: outdent_to_row,
1988 delta: Ordering::Equal,
1989 within_error,
1990 })
1991 } else if outdent_from_prev_row {
1992 Some(IndentSuggestion {
1993 basis_row: prev_row,
1994 delta: Ordering::Less,
1995 within_error,
1996 })
1997 } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
1998 {
1999 Some(IndentSuggestion {
2000 basis_row: prev_row,
2001 delta: Ordering::Equal,
2002 within_error,
2003 })
2004 } else {
2005 None
2006 };
2007
2008 prev_row = row;
2009 prev_row_start = row_start;
2010 suggestion
2011 }))
2012 }
2013
2014 fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2015 while row > 0 {
2016 row -= 1;
2017 if !self.is_line_blank(row) {
2018 return Some(row);
2019 }
2020 }
2021 None
2022 }
2023
2024 pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
2025 let range = range.start.to_offset(self)..range.end.to_offset(self);
2026
2027 let mut syntax = None;
2028 let mut diagnostic_endpoints = Vec::new();
2029 if language_aware {
2030 let captures = self.syntax.captures(range.clone(), &self.text, |grammar| {
2031 grammar.highlights_query.as_ref()
2032 });
2033 let highlight_maps = captures
2034 .grammars()
2035 .into_iter()
2036 .map(|grammar| grammar.highlight_map())
2037 .collect();
2038 syntax = Some((captures, highlight_maps));
2039 for entry in self.diagnostics_in_range::<_, usize>(range.clone(), false) {
2040 diagnostic_endpoints.push(DiagnosticEndpoint {
2041 offset: entry.range.start,
2042 is_start: true,
2043 severity: entry.diagnostic.severity,
2044 is_unnecessary: entry.diagnostic.is_unnecessary,
2045 });
2046 diagnostic_endpoints.push(DiagnosticEndpoint {
2047 offset: entry.range.end,
2048 is_start: false,
2049 severity: entry.diagnostic.severity,
2050 is_unnecessary: entry.diagnostic.is_unnecessary,
2051 });
2052 }
2053 diagnostic_endpoints
2054 .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
2055 }
2056
2057 BufferChunks::new(self.text.as_rope(), range, syntax, diagnostic_endpoints)
2058 }
2059
2060 pub fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
2061 let mut line = String::new();
2062 let mut row = range.start.row;
2063 for chunk in self
2064 .as_rope()
2065 .chunks_in_range(range.to_offset(self))
2066 .chain(["\n"])
2067 {
2068 for (newline_ix, text) in chunk.split('\n').enumerate() {
2069 if newline_ix > 0 {
2070 callback(row, &line);
2071 row += 1;
2072 line.clear();
2073 }
2074 line.push_str(text);
2075 }
2076 }
2077 }
2078
2079 pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
2080 let offset = position.to_offset(self);
2081 self.syntax
2082 .layers_for_range(offset..offset, &self.text)
2083 .filter(|l| l.node.end_byte() > offset)
2084 .last()
2085 .map(|info| info.language)
2086 .or(self.language.as_ref())
2087 }
2088
2089 pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
2090 let offset = position.to_offset(self);
2091
2092 if let Some(layer_info) = self
2093 .syntax
2094 .layers_for_range(offset..offset, &self.text)
2095 .filter(|l| l.node.end_byte() > offset)
2096 .last()
2097 {
2098 Some(LanguageScope {
2099 language: layer_info.language.clone(),
2100 override_id: layer_info.override_id(offset, &self.text),
2101 })
2102 } else {
2103 self.language.clone().map(|language| LanguageScope {
2104 language,
2105 override_id: None,
2106 })
2107 }
2108 }
2109
2110 pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2111 let mut start = start.to_offset(self);
2112 let mut end = start;
2113 let mut next_chars = self.chars_at(start).peekable();
2114 let mut prev_chars = self.reversed_chars_at(start).peekable();
2115 let word_kind = cmp::max(
2116 prev_chars.peek().copied().map(char_kind),
2117 next_chars.peek().copied().map(char_kind),
2118 );
2119
2120 for ch in prev_chars {
2121 if Some(char_kind(ch)) == word_kind && ch != '\n' {
2122 start -= ch.len_utf8();
2123 } else {
2124 break;
2125 }
2126 }
2127
2128 for ch in next_chars {
2129 if Some(char_kind(ch)) == word_kind && ch != '\n' {
2130 end += ch.len_utf8();
2131 } else {
2132 break;
2133 }
2134 }
2135
2136 (start..end, word_kind)
2137 }
2138
2139 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2140 let range = range.start.to_offset(self)..range.end.to_offset(self);
2141 let mut result: Option<Range<usize>> = None;
2142 'outer: for layer in self.syntax.layers_for_range(range.clone(), &self.text) {
2143 let mut cursor = layer.node.walk();
2144
2145 // Descend to the first leaf that touches the start of the range,
2146 // and if the range is non-empty, extends beyond the start.
2147 while cursor.goto_first_child_for_byte(range.start).is_some() {
2148 if !range.is_empty() && cursor.node().end_byte() == range.start {
2149 cursor.goto_next_sibling();
2150 }
2151 }
2152
2153 // Ascend to the smallest ancestor that strictly contains the range.
2154 loop {
2155 let node_range = cursor.node().byte_range();
2156 if node_range.start <= range.start
2157 && node_range.end >= range.end
2158 && node_range.len() > range.len()
2159 {
2160 break;
2161 }
2162 if !cursor.goto_parent() {
2163 continue 'outer;
2164 }
2165 }
2166
2167 let left_node = cursor.node();
2168 let mut layer_result = left_node.byte_range();
2169
2170 // For an empty range, try to find another node immediately to the right of the range.
2171 if left_node.end_byte() == range.start {
2172 let mut right_node = None;
2173 while !cursor.goto_next_sibling() {
2174 if !cursor.goto_parent() {
2175 break;
2176 }
2177 }
2178
2179 while cursor.node().start_byte() == range.start {
2180 right_node = Some(cursor.node());
2181 if !cursor.goto_first_child() {
2182 break;
2183 }
2184 }
2185
2186 // If there is a candidate node on both sides of the (empty) range, then
2187 // decide between the two by favoring a named node over an anonymous token.
2188 // If both nodes are the same in that regard, favor the right one.
2189 if let Some(right_node) = right_node {
2190 if right_node.is_named() || !left_node.is_named() {
2191 layer_result = right_node.byte_range();
2192 }
2193 }
2194 }
2195
2196 if let Some(previous_result) = &result {
2197 if previous_result.len() < layer_result.len() {
2198 continue;
2199 }
2200 }
2201 result = Some(layer_result);
2202 }
2203
2204 result
2205 }
2206
2207 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2208 self.outline_items_containing(0..self.len(), theme)
2209 .map(Outline::new)
2210 }
2211
2212 pub fn symbols_containing<T: ToOffset>(
2213 &self,
2214 position: T,
2215 theme: Option<&SyntaxTheme>,
2216 ) -> Option<Vec<OutlineItem<Anchor>>> {
2217 let position = position.to_offset(self);
2218 let mut items = self.outline_items_containing(
2219 position.saturating_sub(1)..self.len().min(position + 1),
2220 theme,
2221 )?;
2222 let mut prev_depth = None;
2223 items.retain(|item| {
2224 let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
2225 prev_depth = Some(item.depth);
2226 result
2227 });
2228 Some(items)
2229 }
2230
2231 fn outline_items_containing(
2232 &self,
2233 range: Range<usize>,
2234 theme: Option<&SyntaxTheme>,
2235 ) -> Option<Vec<OutlineItem<Anchor>>> {
2236 let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2237 grammar.outline_config.as_ref().map(|c| &c.query)
2238 });
2239 let configs = matches
2240 .grammars()
2241 .iter()
2242 .map(|g| g.outline_config.as_ref().unwrap())
2243 .collect::<Vec<_>>();
2244
2245 let mut chunks = self.chunks(0..self.len(), true);
2246 let mut stack = Vec::<Range<usize>>::new();
2247 let mut items = Vec::new();
2248 while let Some(mat) = matches.peek() {
2249 let config = &configs[mat.grammar_index];
2250 let item_node = mat.captures.iter().find_map(|cap| {
2251 if cap.index == config.item_capture_ix {
2252 Some(cap.node)
2253 } else {
2254 None
2255 }
2256 })?;
2257
2258 let item_range = item_node.byte_range();
2259 if item_range.end < range.start || item_range.start > range.end {
2260 matches.advance();
2261 continue;
2262 }
2263
2264 let mut text = String::new();
2265 let mut name_ranges = Vec::new();
2266 let mut highlight_ranges = Vec::new();
2267 for capture in mat.captures {
2268 let node_is_name;
2269 if capture.index == config.name_capture_ix {
2270 node_is_name = true;
2271 } else if Some(capture.index) == config.context_capture_ix {
2272 node_is_name = false;
2273 } else {
2274 continue;
2275 }
2276
2277 let mut range = capture.node.start_byte()..capture.node.end_byte();
2278 let start = capture.node.start_position();
2279 if capture.node.end_position().row > start.row {
2280 range.end =
2281 range.start + self.line_len(start.row as u32) as usize - start.column;
2282 }
2283
2284 if !text.is_empty() {
2285 text.push(' ');
2286 }
2287 if node_is_name {
2288 let mut start = text.len();
2289 let end = start + range.len();
2290
2291 // When multiple names are captured, then the matcheable text
2292 // includes the whitespace in between the names.
2293 if !name_ranges.is_empty() {
2294 start -= 1;
2295 }
2296
2297 name_ranges.push(start..end);
2298 }
2299
2300 let mut offset = range.start;
2301 chunks.seek(offset);
2302 for mut chunk in chunks.by_ref() {
2303 if chunk.text.len() > range.end - offset {
2304 chunk.text = &chunk.text[0..(range.end - offset)];
2305 offset = range.end;
2306 } else {
2307 offset += chunk.text.len();
2308 }
2309 let style = chunk
2310 .syntax_highlight_id
2311 .zip(theme)
2312 .and_then(|(highlight, theme)| highlight.style(theme));
2313 if let Some(style) = style {
2314 let start = text.len();
2315 let end = start + chunk.text.len();
2316 highlight_ranges.push((start..end, style));
2317 }
2318 text.push_str(chunk.text);
2319 if offset >= range.end {
2320 break;
2321 }
2322 }
2323 }
2324
2325 matches.advance();
2326 while stack.last().map_or(false, |prev_range| {
2327 prev_range.start > item_range.start || prev_range.end < item_range.end
2328 }) {
2329 stack.pop();
2330 }
2331 stack.push(item_range.clone());
2332
2333 items.push(OutlineItem {
2334 depth: stack.len() - 1,
2335 range: self.anchor_after(item_range.start)..self.anchor_before(item_range.end),
2336 text,
2337 highlight_ranges,
2338 name_ranges,
2339 })
2340 }
2341 Some(items)
2342 }
2343
2344 pub fn enclosing_bracket_ranges<T: ToOffset>(
2345 &self,
2346 range: Range<T>,
2347 ) -> Option<(Range<usize>, Range<usize>)> {
2348 // Find bracket pairs that *inclusively* contain the given range.
2349 let range = range.start.to_offset(self)..range.end.to_offset(self);
2350 let mut matches = self.syntax.matches(
2351 range.start.saturating_sub(1)..self.len().min(range.end + 1),
2352 &self.text,
2353 |grammar| grammar.brackets_config.as_ref().map(|c| &c.query),
2354 );
2355 let configs = matches
2356 .grammars()
2357 .iter()
2358 .map(|grammar| grammar.brackets_config.as_ref().unwrap())
2359 .collect::<Vec<_>>();
2360
2361 // Get the ranges of the innermost pair of brackets.
2362 let mut result: Option<(Range<usize>, Range<usize>)> = None;
2363 while let Some(mat) = matches.peek() {
2364 let mut open = None;
2365 let mut close = None;
2366 let config = &configs[mat.grammar_index];
2367 for capture in mat.captures {
2368 if capture.index == config.open_capture_ix {
2369 open = Some(capture.node.byte_range());
2370 } else if capture.index == config.close_capture_ix {
2371 close = Some(capture.node.byte_range());
2372 }
2373 }
2374
2375 matches.advance();
2376
2377 let Some((open, close)) = open.zip(close) else { continue };
2378 if open.start > range.start || close.end < range.end {
2379 continue;
2380 }
2381 let len = close.end - open.start;
2382
2383 if let Some((existing_open, existing_close)) = &result {
2384 let existing_len = existing_close.end - existing_open.start;
2385 if len > existing_len {
2386 continue;
2387 }
2388 }
2389
2390 result = Some((open, close));
2391 }
2392
2393 result
2394 }
2395
2396 #[allow(clippy::type_complexity)]
2397 pub fn remote_selections_in_range(
2398 &self,
2399 range: Range<Anchor>,
2400 ) -> impl Iterator<
2401 Item = (
2402 ReplicaId,
2403 bool,
2404 CursorShape,
2405 impl Iterator<Item = &Selection<Anchor>> + '_,
2406 ),
2407 > + '_ {
2408 self.remote_selections
2409 .iter()
2410 .filter(|(replica_id, set)| {
2411 **replica_id != self.text.replica_id() && !set.selections.is_empty()
2412 })
2413 .map(move |(replica_id, set)| {
2414 let start_ix = match set.selections.binary_search_by(|probe| {
2415 probe.end.cmp(&range.start, self).then(Ordering::Greater)
2416 }) {
2417 Ok(ix) | Err(ix) => ix,
2418 };
2419 let end_ix = match set.selections.binary_search_by(|probe| {
2420 probe.start.cmp(&range.end, self).then(Ordering::Less)
2421 }) {
2422 Ok(ix) | Err(ix) => ix,
2423 };
2424
2425 (
2426 *replica_id,
2427 set.line_mode,
2428 set.cursor_shape,
2429 set.selections[start_ix..end_ix].iter(),
2430 )
2431 })
2432 }
2433
2434 pub fn git_diff_hunks_in_row_range<'a>(
2435 &'a self,
2436 range: Range<u32>,
2437 reversed: bool,
2438 ) -> impl 'a + Iterator<Item = git::diff::DiffHunk<u32>> {
2439 self.git_diff.hunks_in_row_range(range, self, reversed)
2440 }
2441
2442 pub fn git_diff_hunks_intersecting_range<'a>(
2443 &'a self,
2444 range: Range<Anchor>,
2445 reversed: bool,
2446 ) -> impl 'a + Iterator<Item = git::diff::DiffHunk<u32>> {
2447 self.git_diff
2448 .hunks_intersecting_range(range, self, reversed)
2449 }
2450
2451 pub fn diagnostics_in_range<'a, T, O>(
2452 &'a self,
2453 search_range: Range<T>,
2454 reversed: bool,
2455 ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2456 where
2457 T: 'a + Clone + ToOffset,
2458 O: 'a + FromAnchor,
2459 {
2460 self.diagnostics.range(search_range, self, true, reversed)
2461 }
2462
2463 pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
2464 let mut groups = Vec::new();
2465 self.diagnostics.groups(&mut groups, self);
2466 groups
2467 }
2468
2469 pub fn diagnostic_group<'a, O>(
2470 &'a self,
2471 group_id: usize,
2472 ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2473 where
2474 O: 'a + FromAnchor,
2475 {
2476 self.diagnostics.group(group_id, self)
2477 }
2478
2479 pub fn diagnostics_update_count(&self) -> usize {
2480 self.diagnostics_update_count
2481 }
2482
2483 pub fn parse_count(&self) -> usize {
2484 self.parse_count
2485 }
2486
2487 pub fn selections_update_count(&self) -> usize {
2488 self.selections_update_count
2489 }
2490
2491 pub fn file(&self) -> Option<&Arc<dyn File>> {
2492 self.file.as_ref()
2493 }
2494
2495 pub fn resolve_file_path(&self, cx: &AppContext, include_root: bool) -> Option<PathBuf> {
2496 if let Some(file) = self.file() {
2497 if file.path().file_name().is_none() || include_root {
2498 Some(file.full_path(cx))
2499 } else {
2500 Some(file.path().to_path_buf())
2501 }
2502 } else {
2503 None
2504 }
2505 }
2506
2507 pub fn file_update_count(&self) -> usize {
2508 self.file_update_count
2509 }
2510
2511 pub fn git_diff_update_count(&self) -> usize {
2512 self.git_diff_update_count
2513 }
2514}
2515
2516fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
2517 indent_size_for_text(text.chars_at(Point::new(row, 0)))
2518}
2519
2520pub fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
2521 let mut result = IndentSize::spaces(0);
2522 for c in text {
2523 let kind = match c {
2524 ' ' => IndentKind::Space,
2525 '\t' => IndentKind::Tab,
2526 _ => break,
2527 };
2528 if result.len == 0 {
2529 result.kind = kind;
2530 }
2531 result.len += 1;
2532 }
2533 result
2534}
2535
2536impl Clone for BufferSnapshot {
2537 fn clone(&self) -> Self {
2538 Self {
2539 text: self.text.clone(),
2540 git_diff: self.git_diff.clone(),
2541 syntax: self.syntax.clone(),
2542 file: self.file.clone(),
2543 remote_selections: self.remote_selections.clone(),
2544 diagnostics: self.diagnostics.clone(),
2545 selections_update_count: self.selections_update_count,
2546 diagnostics_update_count: self.diagnostics_update_count,
2547 file_update_count: self.file_update_count,
2548 git_diff_update_count: self.git_diff_update_count,
2549 language: self.language.clone(),
2550 parse_count: self.parse_count,
2551 }
2552 }
2553}
2554
2555impl Deref for BufferSnapshot {
2556 type Target = text::BufferSnapshot;
2557
2558 fn deref(&self) -> &Self::Target {
2559 &self.text
2560 }
2561}
2562
2563unsafe impl<'a> Send for BufferChunks<'a> {}
2564
2565impl<'a> BufferChunks<'a> {
2566 pub(crate) fn new(
2567 text: &'a Rope,
2568 range: Range<usize>,
2569 syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
2570 diagnostic_endpoints: Vec<DiagnosticEndpoint>,
2571 ) -> Self {
2572 let mut highlights = None;
2573 if let Some((captures, highlight_maps)) = syntax {
2574 highlights = Some(BufferChunkHighlights {
2575 captures,
2576 next_capture: None,
2577 stack: Default::default(),
2578 highlight_maps,
2579 })
2580 }
2581
2582 let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
2583 let chunks = text.chunks_in_range(range.clone());
2584
2585 BufferChunks {
2586 range,
2587 chunks,
2588 diagnostic_endpoints,
2589 error_depth: 0,
2590 warning_depth: 0,
2591 information_depth: 0,
2592 hint_depth: 0,
2593 unnecessary_depth: 0,
2594 highlights,
2595 }
2596 }
2597
2598 pub fn seek(&mut self, offset: usize) {
2599 self.range.start = offset;
2600 self.chunks.seek(self.range.start);
2601 if let Some(highlights) = self.highlights.as_mut() {
2602 highlights
2603 .stack
2604 .retain(|(end_offset, _)| *end_offset > offset);
2605 if let Some(capture) = &highlights.next_capture {
2606 if offset >= capture.node.start_byte() {
2607 let next_capture_end = capture.node.end_byte();
2608 if offset < next_capture_end {
2609 highlights.stack.push((
2610 next_capture_end,
2611 highlights.highlight_maps[capture.grammar_index].get(capture.index),
2612 ));
2613 }
2614 highlights.next_capture.take();
2615 }
2616 }
2617 highlights.captures.set_byte_range(self.range.clone());
2618 }
2619 }
2620
2621 pub fn offset(&self) -> usize {
2622 self.range.start
2623 }
2624
2625 fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
2626 let depth = match endpoint.severity {
2627 DiagnosticSeverity::ERROR => &mut self.error_depth,
2628 DiagnosticSeverity::WARNING => &mut self.warning_depth,
2629 DiagnosticSeverity::INFORMATION => &mut self.information_depth,
2630 DiagnosticSeverity::HINT => &mut self.hint_depth,
2631 _ => return,
2632 };
2633 if endpoint.is_start {
2634 *depth += 1;
2635 } else {
2636 *depth -= 1;
2637 }
2638
2639 if endpoint.is_unnecessary {
2640 if endpoint.is_start {
2641 self.unnecessary_depth += 1;
2642 } else {
2643 self.unnecessary_depth -= 1;
2644 }
2645 }
2646 }
2647
2648 fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
2649 if self.error_depth > 0 {
2650 Some(DiagnosticSeverity::ERROR)
2651 } else if self.warning_depth > 0 {
2652 Some(DiagnosticSeverity::WARNING)
2653 } else if self.information_depth > 0 {
2654 Some(DiagnosticSeverity::INFORMATION)
2655 } else if self.hint_depth > 0 {
2656 Some(DiagnosticSeverity::HINT)
2657 } else {
2658 None
2659 }
2660 }
2661
2662 fn current_code_is_unnecessary(&self) -> bool {
2663 self.unnecessary_depth > 0
2664 }
2665}
2666
2667impl<'a> Iterator for BufferChunks<'a> {
2668 type Item = Chunk<'a>;
2669
2670 fn next(&mut self) -> Option<Self::Item> {
2671 let mut next_capture_start = usize::MAX;
2672 let mut next_diagnostic_endpoint = usize::MAX;
2673
2674 if let Some(highlights) = self.highlights.as_mut() {
2675 while let Some((parent_capture_end, _)) = highlights.stack.last() {
2676 if *parent_capture_end <= self.range.start {
2677 highlights.stack.pop();
2678 } else {
2679 break;
2680 }
2681 }
2682
2683 if highlights.next_capture.is_none() {
2684 highlights.next_capture = highlights.captures.next();
2685 }
2686
2687 while let Some(capture) = highlights.next_capture.as_ref() {
2688 if self.range.start < capture.node.start_byte() {
2689 next_capture_start = capture.node.start_byte();
2690 break;
2691 } else {
2692 let highlight_id =
2693 highlights.highlight_maps[capture.grammar_index].get(capture.index);
2694 highlights
2695 .stack
2696 .push((capture.node.end_byte(), highlight_id));
2697 highlights.next_capture = highlights.captures.next();
2698 }
2699 }
2700 }
2701
2702 while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
2703 if endpoint.offset <= self.range.start {
2704 self.update_diagnostic_depths(endpoint);
2705 self.diagnostic_endpoints.next();
2706 } else {
2707 next_diagnostic_endpoint = endpoint.offset;
2708 break;
2709 }
2710 }
2711
2712 if let Some(chunk) = self.chunks.peek() {
2713 let chunk_start = self.range.start;
2714 let mut chunk_end = (self.chunks.offset() + chunk.len())
2715 .min(next_capture_start)
2716 .min(next_diagnostic_endpoint);
2717 let mut highlight_id = None;
2718 if let Some(highlights) = self.highlights.as_ref() {
2719 if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
2720 chunk_end = chunk_end.min(*parent_capture_end);
2721 highlight_id = Some(*parent_highlight_id);
2722 }
2723 }
2724
2725 let slice =
2726 &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2727 self.range.start = chunk_end;
2728 if self.range.start == self.chunks.offset() + chunk.len() {
2729 self.chunks.next().unwrap();
2730 }
2731
2732 Some(Chunk {
2733 text: slice,
2734 syntax_highlight_id: highlight_id,
2735 highlight_style: None,
2736 diagnostic_severity: self.current_diagnostic_severity(),
2737 is_unnecessary: self.current_code_is_unnecessary(),
2738 })
2739 } else {
2740 None
2741 }
2742 }
2743}
2744
2745impl operation_queue::Operation for Operation {
2746 fn lamport_timestamp(&self) -> clock::Lamport {
2747 match self {
2748 Operation::Buffer(_) => {
2749 unreachable!("buffer operations should never be deferred at this layer")
2750 }
2751 Operation::UpdateDiagnostics {
2752 lamport_timestamp, ..
2753 }
2754 | Operation::UpdateSelections {
2755 lamport_timestamp, ..
2756 }
2757 | Operation::UpdateCompletionTriggers {
2758 lamport_timestamp, ..
2759 } => *lamport_timestamp,
2760 }
2761 }
2762}
2763
2764impl Default for Diagnostic {
2765 fn default() -> Self {
2766 Self {
2767 code: None,
2768 severity: DiagnosticSeverity::ERROR,
2769 message: Default::default(),
2770 group_id: 0,
2771 is_primary: false,
2772 is_valid: true,
2773 is_disk_based: false,
2774 is_unnecessary: false,
2775 }
2776 }
2777}
2778
2779impl IndentSize {
2780 pub fn spaces(len: u32) -> Self {
2781 Self {
2782 len,
2783 kind: IndentKind::Space,
2784 }
2785 }
2786
2787 pub fn tab() -> Self {
2788 Self {
2789 len: 1,
2790 kind: IndentKind::Tab,
2791 }
2792 }
2793
2794 pub fn chars(&self) -> impl Iterator<Item = char> {
2795 iter::repeat(self.char()).take(self.len as usize)
2796 }
2797
2798 pub fn char(&self) -> char {
2799 match self.kind {
2800 IndentKind::Space => ' ',
2801 IndentKind::Tab => '\t',
2802 }
2803 }
2804
2805 pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
2806 match direction {
2807 Ordering::Less => {
2808 if self.kind == size.kind && self.len >= size.len {
2809 self.len -= size.len;
2810 }
2811 }
2812 Ordering::Equal => {}
2813 Ordering::Greater => {
2814 if self.len == 0 {
2815 self = size;
2816 } else if self.kind == size.kind {
2817 self.len += size.len;
2818 }
2819 }
2820 }
2821 self
2822 }
2823}
2824
2825impl Completion {
2826 pub fn sort_key(&self) -> (usize, &str) {
2827 let kind_key = match self.lsp_completion.kind {
2828 Some(lsp::CompletionItemKind::VARIABLE) => 0,
2829 _ => 1,
2830 };
2831 (kind_key, &self.label.text[self.label.filter_range.clone()])
2832 }
2833
2834 pub fn is_snippet(&self) -> bool {
2835 self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
2836 }
2837}
2838
2839pub fn contiguous_ranges(
2840 values: impl Iterator<Item = u32>,
2841 max_len: usize,
2842) -> impl Iterator<Item = Range<u32>> {
2843 let mut values = values;
2844 let mut current_range: Option<Range<u32>> = None;
2845 std::iter::from_fn(move || loop {
2846 if let Some(value) = values.next() {
2847 if let Some(range) = &mut current_range {
2848 if value == range.end && range.len() < max_len {
2849 range.end += 1;
2850 continue;
2851 }
2852 }
2853
2854 let prev_range = current_range.clone();
2855 current_range = Some(value..(value + 1));
2856 if prev_range.is_some() {
2857 return prev_range;
2858 }
2859 } else {
2860 return current_range.take();
2861 }
2862 })
2863}
2864
2865pub fn char_kind(c: char) -> CharKind {
2866 if c.is_whitespace() {
2867 CharKind::Whitespace
2868 } else if c.is_alphanumeric() || c == '_' {
2869 CharKind::Word
2870 } else {
2871 CharKind::Punctuation
2872 }
2873}