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