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