1pub use crate::{
2 diagnostic_set::DiagnosticSet,
3 highlight_map::{HighlightId, HighlightMap},
4 markdown::ParsedMarkdown,
5 proto, Grammar, Language, LanguageRegistry,
6};
7use crate::{
8 diagnostic_set::{DiagnosticEntry, DiagnosticGroup},
9 language_settings::{language_settings, IndentGuideSettings, LanguageSettings},
10 markdown::parse_markdown,
11 outline::OutlineItem,
12 syntax_map::{
13 SyntaxLayer, SyntaxMap, SyntaxMapCapture, SyntaxMapCaptures, SyntaxMapMatch,
14 SyntaxMapMatches, SyntaxSnapshot, ToTreeSitterPoint,
15 },
16 task_context::RunnableRange,
17 LanguageScope, Outline, OutlineConfig, RunnableCapture, RunnableTag,
18};
19use anyhow::{anyhow, Context, Result};
20use async_watch as watch;
21pub use clock::ReplicaId;
22use futures::channel::oneshot;
23use gpui::{
24 AnyElement, AppContext, EventEmitter, HighlightStyle, ModelContext, Task, TaskLabel,
25 WindowContext,
26};
27use lazy_static::lazy_static;
28use lsp::LanguageServerId;
29use parking_lot::Mutex;
30use serde_json::Value;
31use similar::{ChangeTag, TextDiff};
32use smallvec::SmallVec;
33use smol::future::yield_now;
34use std::{
35 any::Any,
36 cell::Cell,
37 cmp::{self, Ordering, Reverse},
38 collections::BTreeMap,
39 ffi::OsStr,
40 fmt,
41 future::Future,
42 iter::{self, Iterator, Peekable},
43 mem,
44 ops::{Deref, Range},
45 path::{Path, PathBuf},
46 str,
47 sync::Arc,
48 time::{Duration, Instant, SystemTime},
49 vec,
50};
51use sum_tree::TreeMap;
52use text::operation_queue::OperationQueue;
53use text::*;
54pub use text::{
55 Anchor, Bias, Buffer as TextBuffer, BufferId, BufferSnapshot as TextBufferSnapshot, Edit,
56 OffsetRangeExt, OffsetUtf16, Patch, Point, PointUtf16, Rope, Selection, SelectionGoal,
57 Subscription, TextDimension, TextSummary, ToOffset, ToOffsetUtf16, ToPoint, ToPointUtf16,
58 Transaction, TransactionId, Unclipped,
59};
60use theme::SyntaxTheme;
61#[cfg(any(test, feature = "test-support"))]
62use util::RandomCharIter;
63use util::RangeExt;
64
65#[cfg(any(test, feature = "test-support"))]
66pub use {tree_sitter_rust, tree_sitter_typescript};
67
68pub use lsp::DiagnosticSeverity;
69
70lazy_static! {
71 /// A label for the background task spawned by the buffer to compute
72 /// a diff against the contents of its file.
73 pub static ref BUFFER_DIFF_TASK: TaskLabel = TaskLabel::new();
74}
75
76/// Indicate whether a [Buffer] has permissions to edit.
77#[derive(PartialEq, Clone, Copy, Debug)]
78pub enum Capability {
79 /// The buffer is a mutable replica.
80 ReadWrite,
81 /// The buffer is a read-only replica.
82 ReadOnly,
83}
84
85pub type BufferRow = u32;
86
87/// An in-memory representation of a source code file, including its text,
88/// syntax trees, git status, and diagnostics.
89pub struct Buffer {
90 text: TextBuffer,
91 diff_base: Option<Rope>,
92 git_diff: git::diff::BufferDiff,
93 file: Option<Arc<dyn File>>,
94 /// The mtime of the file when this buffer was last loaded from
95 /// or saved to disk.
96 saved_mtime: Option<SystemTime>,
97 /// The version vector when this buffer was last loaded from
98 /// or saved to disk.
99 saved_version: clock::Global,
100 transaction_depth: usize,
101 was_dirty_before_starting_transaction: Option<bool>,
102 reload_task: Option<Task<Result<()>>>,
103 language: Option<Arc<Language>>,
104 autoindent_requests: Vec<Arc<AutoindentRequest>>,
105 pending_autoindent: Option<Task<()>>,
106 sync_parse_timeout: Duration,
107 syntax_map: Mutex<SyntaxMap>,
108 parsing_in_background: bool,
109 parse_status: (watch::Sender<ParseStatus>, watch::Receiver<ParseStatus>),
110 non_text_state_update_count: usize,
111 diagnostics: SmallVec<[(LanguageServerId, DiagnosticSet); 2]>,
112 remote_selections: TreeMap<ReplicaId, SelectionSet>,
113 diagnostics_timestamp: clock::Lamport,
114 completion_triggers: Vec<String>,
115 completion_triggers_timestamp: clock::Lamport,
116 deferred_ops: OperationQueue<Operation>,
117 capability: Capability,
118 has_conflict: bool,
119 diff_base_version: usize,
120 /// Memoize calls to has_changes_since(saved_version).
121 /// The contents of a cell are (self.version, has_changes) at the time of a last call.
122 has_unsaved_edits: Cell<(clock::Global, bool)>,
123}
124
125#[derive(Copy, Clone, Debug, PartialEq, Eq)]
126pub enum ParseStatus {
127 Idle,
128 Parsing,
129}
130
131/// An immutable, cheaply cloneable representation of a fixed
132/// state of a buffer.
133pub struct BufferSnapshot {
134 text: text::BufferSnapshot,
135 git_diff: git::diff::BufferDiff,
136 pub(crate) syntax: SyntaxSnapshot,
137 file: Option<Arc<dyn File>>,
138 diagnostics: SmallVec<[(LanguageServerId, DiagnosticSet); 2]>,
139 remote_selections: TreeMap<ReplicaId, SelectionSet>,
140 language: Option<Arc<Language>>,
141 non_text_state_update_count: usize,
142}
143
144/// The kind and amount of indentation in a particular line. For now,
145/// assumes that indentation is all the same character.
146#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
147pub struct IndentSize {
148 /// The number of bytes that comprise the indentation.
149 pub len: u32,
150 /// The kind of whitespace used for indentation.
151 pub kind: IndentKind,
152}
153
154/// A whitespace character that's used for indentation.
155#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
156pub enum IndentKind {
157 /// An ASCII space character.
158 #[default]
159 Space,
160 /// An ASCII tab character.
161 Tab,
162}
163
164/// The shape of a selection cursor.
165#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
166pub enum CursorShape {
167 /// A vertical bar
168 #[default]
169 Bar,
170 /// A block that surrounds the following character
171 Block,
172 /// An underline that runs along the following character
173 Underscore,
174 /// A box drawn around the following character
175 Hollow,
176}
177
178#[derive(Clone, Debug)]
179struct SelectionSet {
180 line_mode: bool,
181 cursor_shape: CursorShape,
182 selections: Arc<[Selection<Anchor>]>,
183 lamport_timestamp: clock::Lamport,
184}
185
186/// A diagnostic associated with a certain range of a buffer.
187#[derive(Clone, Debug, PartialEq, Eq)]
188pub struct Diagnostic {
189 /// The name of the service that produced this diagnostic.
190 pub source: Option<String>,
191 /// A machine-readable code that identifies this diagnostic.
192 pub code: Option<String>,
193 /// Whether this diagnostic is a hint, warning, or error.
194 pub severity: DiagnosticSeverity,
195 /// The human-readable message associated with this diagnostic.
196 pub message: String,
197 /// An id that identifies the group to which this diagnostic belongs.
198 ///
199 /// When a language server produces a diagnostic with
200 /// one or more associated diagnostics, those diagnostics are all
201 /// assigned a single group id.
202 pub group_id: usize,
203 /// Whether this diagnostic is the primary diagnostic for its group.
204 ///
205 /// In a given group, the primary diagnostic is the top-level diagnostic
206 /// returned by the language server. The non-primary diagnostics are the
207 /// associated diagnostics.
208 pub is_primary: bool,
209 /// Whether this diagnostic is considered to originate from an analysis of
210 /// files on disk, as opposed to any unsaved buffer contents. This is a
211 /// property of a given diagnostic source, and is configured for a given
212 /// language server via the [`LspAdapter::disk_based_diagnostic_sources`](crate::LspAdapter::disk_based_diagnostic_sources) method
213 /// for the language server.
214 pub is_disk_based: bool,
215 /// Whether this diagnostic marks unnecessary code.
216 pub is_unnecessary: bool,
217 /// Data from language server that produced this diagnostic. Passed back to the LS when we request code actions for this diagnostic.
218 pub data: Option<Value>,
219}
220
221/// TODO - move this into the `project` crate and make it private.
222pub async fn prepare_completion_documentation(
223 documentation: &lsp::Documentation,
224 language_registry: &Arc<LanguageRegistry>,
225 language: Option<Arc<Language>>,
226) -> Documentation {
227 match documentation {
228 lsp::Documentation::String(text) => {
229 if text.lines().count() <= 1 {
230 Documentation::SingleLine(text.clone())
231 } else {
232 Documentation::MultiLinePlainText(text.clone())
233 }
234 }
235
236 lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
237 lsp::MarkupKind::PlainText => {
238 if value.lines().count() <= 1 {
239 Documentation::SingleLine(value.clone())
240 } else {
241 Documentation::MultiLinePlainText(value.clone())
242 }
243 }
244
245 lsp::MarkupKind::Markdown => {
246 let parsed = parse_markdown(value, language_registry, language).await;
247 Documentation::MultiLineMarkdown(parsed)
248 }
249 },
250 }
251}
252
253/// Documentation associated with a [`Completion`].
254#[derive(Clone, Debug)]
255pub enum Documentation {
256 /// There is no documentation for this completion.
257 Undocumented,
258 /// A single line of documentation.
259 SingleLine(String),
260 /// Multiple lines of plain text documentation.
261 MultiLinePlainText(String),
262 /// Markdown documentation.
263 MultiLineMarkdown(ParsedMarkdown),
264}
265
266/// An operation used to synchronize this buffer with its other replicas.
267#[derive(Clone, Debug, PartialEq)]
268pub enum Operation {
269 /// A text operation.
270 Buffer(text::Operation),
271
272 /// An update to the buffer's diagnostics.
273 UpdateDiagnostics {
274 /// The id of the language server that produced the new diagnostics.
275 server_id: LanguageServerId,
276 /// The diagnostics.
277 diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
278 /// The buffer's lamport timestamp.
279 lamport_timestamp: clock::Lamport,
280 },
281
282 /// An update to the most recent selections in this buffer.
283 UpdateSelections {
284 /// The selections.
285 selections: Arc<[Selection<Anchor>]>,
286 /// The buffer's lamport timestamp.
287 lamport_timestamp: clock::Lamport,
288 /// Whether the selections are in 'line mode'.
289 line_mode: bool,
290 /// The [`CursorShape`] associated with these selections.
291 cursor_shape: CursorShape,
292 },
293
294 /// An update to the characters that should trigger autocompletion
295 /// for this buffer.
296 UpdateCompletionTriggers {
297 /// The characters that trigger autocompletion.
298 triggers: Vec<String>,
299 /// The buffer's lamport timestamp.
300 lamport_timestamp: clock::Lamport,
301 },
302}
303
304/// An event that occurs in a buffer.
305#[derive(Clone, Debug, PartialEq)]
306pub enum Event {
307 /// The buffer was changed in a way that must be
308 /// propagated to its other replicas.
309 Operation(Operation),
310 /// The buffer was edited.
311 Edited,
312 /// The buffer's `dirty` bit changed.
313 DirtyChanged,
314 /// The buffer was saved.
315 Saved,
316 /// The buffer's file was changed on disk.
317 FileHandleChanged,
318 /// The buffer was reloaded.
319 Reloaded,
320 /// The buffer's diff_base changed.
321 DiffBaseChanged,
322 /// Buffer's excerpts for a certain diff base were recalculated.
323 DiffUpdated,
324 /// The buffer's language was changed.
325 LanguageChanged,
326 /// The buffer's syntax trees were updated.
327 Reparsed,
328 /// The buffer's diagnostics were updated.
329 DiagnosticsUpdated,
330 /// The buffer gained or lost editing capabilities.
331 CapabilityChanged,
332 /// The buffer was explicitly requested to close.
333 Closed,
334}
335
336/// The file associated with a buffer.
337pub trait File: Send + Sync {
338 /// Returns the [`LocalFile`] associated with this file, if the
339 /// file is local.
340 fn as_local(&self) -> Option<&dyn LocalFile>;
341
342 /// Returns whether this file is local.
343 fn is_local(&self) -> bool {
344 self.as_local().is_some()
345 }
346
347 /// Returns the file's mtime.
348 fn mtime(&self) -> Option<SystemTime>;
349
350 /// Returns the path of this file relative to the worktree's root directory.
351 fn path(&self) -> &Arc<Path>;
352
353 /// Returns the path of this file relative to the worktree's parent directory (this means it
354 /// includes the name of the worktree's root folder).
355 fn full_path(&self, cx: &AppContext) -> PathBuf;
356
357 /// Returns the last component of this handle's absolute path. If this handle refers to the root
358 /// of its worktree, then this method will return the name of the worktree itself.
359 fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr;
360
361 /// Returns the id of the worktree to which this file belongs.
362 ///
363 /// This is needed for looking up project-specific settings.
364 fn worktree_id(&self) -> usize;
365
366 /// Returns whether the file has been deleted.
367 fn is_deleted(&self) -> bool;
368
369 /// Returns whether the file existed on disk at one point
370 fn is_created(&self) -> bool {
371 self.mtime().is_some()
372 }
373
374 /// Converts this file into an [`Any`] trait object.
375 fn as_any(&self) -> &dyn Any;
376
377 /// Converts this file into a protobuf message.
378 fn to_proto(&self, cx: &AppContext) -> rpc::proto::File;
379
380 /// Return whether Zed considers this to be a private file.
381 fn is_private(&self) -> bool;
382}
383
384/// The file associated with a buffer, in the case where the file is on the local disk.
385pub trait LocalFile: File {
386 /// Returns the absolute path of this file.
387 fn abs_path(&self, cx: &AppContext) -> PathBuf;
388
389 /// Loads the file's contents from disk.
390 fn load(&self, cx: &AppContext) -> Task<Result<String>>;
391
392 /// Returns true if the file should not be shared with collaborators.
393 fn is_private(&self, _: &AppContext) -> bool {
394 false
395 }
396}
397
398/// The auto-indent behavior associated with an editing operation.
399/// For some editing operations, each affected line of text has its
400/// indentation recomputed. For other operations, the entire block
401/// of edited text is adjusted uniformly.
402#[derive(Clone, Debug)]
403pub enum AutoindentMode {
404 /// Indent each line of inserted text.
405 EachLine,
406 /// Apply the same indentation adjustment to all of the lines
407 /// in a given insertion.
408 Block {
409 /// The original indentation level of the first line of each
410 /// insertion, if it has been copied.
411 original_indent_columns: Vec<u32>,
412 },
413}
414
415#[derive(Clone)]
416struct AutoindentRequest {
417 before_edit: BufferSnapshot,
418 entries: Vec<AutoindentRequestEntry>,
419 is_block_mode: bool,
420}
421
422#[derive(Clone)]
423struct AutoindentRequestEntry {
424 /// A range of the buffer whose indentation should be adjusted.
425 range: Range<Anchor>,
426 /// Whether or not these lines should be considered brand new, for the
427 /// purpose of auto-indent. When text is not new, its indentation will
428 /// only be adjusted if the suggested indentation level has *changed*
429 /// since the edit was made.
430 first_line_is_new: bool,
431 indent_size: IndentSize,
432 original_indent_column: Option<u32>,
433}
434
435#[derive(Debug)]
436struct IndentSuggestion {
437 basis_row: u32,
438 delta: Ordering,
439 within_error: bool,
440}
441
442struct BufferChunkHighlights<'a> {
443 captures: SyntaxMapCaptures<'a>,
444 next_capture: Option<SyntaxMapCapture<'a>>,
445 stack: Vec<(usize, HighlightId)>,
446 highlight_maps: Vec<HighlightMap>,
447}
448
449/// An iterator that yields chunks of a buffer's text, along with their
450/// syntax highlights and diagnostic status.
451pub struct BufferChunks<'a> {
452 buffer_snapshot: Option<&'a BufferSnapshot>,
453 range: Range<usize>,
454 chunks: text::Chunks<'a>,
455 diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
456 error_depth: usize,
457 warning_depth: usize,
458 information_depth: usize,
459 hint_depth: usize,
460 unnecessary_depth: usize,
461 highlights: Option<BufferChunkHighlights<'a>>,
462}
463
464/// A chunk of a buffer's text, along with its syntax highlight and
465/// diagnostic status.
466#[derive(Clone, Debug, Default)]
467pub struct Chunk<'a> {
468 /// The text of the chunk.
469 pub text: &'a str,
470 /// The syntax highlighting style of the chunk.
471 pub syntax_highlight_id: Option<HighlightId>,
472 /// The highlight style that has been applied to this chunk in
473 /// the editor.
474 pub highlight_style: Option<HighlightStyle>,
475 /// The severity of diagnostic associated with this chunk, if any.
476 pub diagnostic_severity: Option<DiagnosticSeverity>,
477 /// Whether this chunk of text is marked as unnecessary.
478 pub is_unnecessary: bool,
479 /// Whether this chunk of text was originally a tab character.
480 pub is_tab: bool,
481 /// An optional recipe for how the chunk should be presented.
482 pub renderer: Option<ChunkRenderer>,
483}
484
485/// A recipe for how the chunk should be presented.
486#[derive(Clone)]
487pub struct ChunkRenderer {
488 /// creates a custom element to represent this chunk.
489 pub render: Arc<dyn Send + Sync + Fn(&mut WindowContext) -> AnyElement>,
490 /// If true, the element is constrained to the shaped width of the text.
491 pub constrain_width: bool,
492}
493
494impl fmt::Debug for ChunkRenderer {
495 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
496 f.debug_struct("ChunkRenderer")
497 .field("constrain_width", &self.constrain_width)
498 .finish()
499 }
500}
501
502/// A set of edits to a given version of a buffer, computed asynchronously.
503#[derive(Debug)]
504pub struct Diff {
505 pub(crate) base_version: clock::Global,
506 line_ending: LineEnding,
507 edits: Vec<(Range<usize>, Arc<str>)>,
508}
509
510#[derive(Clone, Copy)]
511pub(crate) struct DiagnosticEndpoint {
512 offset: usize,
513 is_start: bool,
514 severity: DiagnosticSeverity,
515 is_unnecessary: bool,
516}
517
518/// A class of characters, used for characterizing a run of text.
519#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug)]
520pub enum CharKind {
521 /// Whitespace.
522 Whitespace,
523 /// Punctuation.
524 Punctuation,
525 /// Word.
526 Word,
527}
528
529/// A runnable is a set of data about a region that could be resolved into a task
530pub struct Runnable {
531 pub tags: SmallVec<[RunnableTag; 1]>,
532 pub language: Arc<Language>,
533 pub buffer: BufferId,
534}
535
536#[derive(Clone, Debug, PartialEq)]
537pub struct IndentGuide {
538 pub buffer_id: BufferId,
539 pub start_row: BufferRow,
540 pub end_row: BufferRow,
541 pub depth: u32,
542 pub tab_size: u32,
543 pub settings: IndentGuideSettings,
544}
545
546impl IndentGuide {
547 pub fn indent_level(&self) -> u32 {
548 self.depth * self.tab_size
549 }
550}
551
552impl Buffer {
553 /// Create a new buffer with the given base text.
554 pub fn local<T: Into<String>>(base_text: T, cx: &mut ModelContext<Self>) -> Self {
555 Self::build(
556 TextBuffer::new(0, cx.entity_id().as_non_zero_u64().into(), base_text.into()),
557 None,
558 None,
559 Capability::ReadWrite,
560 )
561 }
562
563 /// Create a new buffer with the given base text that has proper line endings and other normalization applied.
564 pub fn local_normalized(
565 base_text_normalized: Rope,
566 line_ending: LineEnding,
567 cx: &mut ModelContext<Self>,
568 ) -> Self {
569 Self::build(
570 TextBuffer::new_normalized(
571 0,
572 cx.entity_id().as_non_zero_u64().into(),
573 line_ending,
574 base_text_normalized,
575 ),
576 None,
577 None,
578 Capability::ReadWrite,
579 )
580 }
581
582 /// Create a new buffer that is a replica of a remote buffer.
583 pub fn remote(
584 remote_id: BufferId,
585 replica_id: ReplicaId,
586 capability: Capability,
587 base_text: impl Into<String>,
588 ) -> Self {
589 Self::build(
590 TextBuffer::new(replica_id, remote_id, base_text.into()),
591 None,
592 None,
593 capability,
594 )
595 }
596
597 /// Create a new buffer that is a replica of a remote buffer, populating its
598 /// state from the given protobuf message.
599 pub fn from_proto(
600 replica_id: ReplicaId,
601 capability: Capability,
602 message: proto::BufferState,
603 file: Option<Arc<dyn File>>,
604 ) -> Result<Self> {
605 let buffer_id = BufferId::new(message.id)
606 .with_context(|| anyhow!("Could not deserialize buffer_id"))?;
607 let buffer = TextBuffer::new(replica_id, buffer_id, message.base_text);
608 let mut this = Self::build(buffer, message.diff_base, file, capability);
609 this.text.set_line_ending(proto::deserialize_line_ending(
610 rpc::proto::LineEnding::from_i32(message.line_ending)
611 .ok_or_else(|| anyhow!("missing line_ending"))?,
612 ));
613 this.saved_version = proto::deserialize_version(&message.saved_version);
614 this.saved_mtime = message.saved_mtime.map(|time| time.into());
615 Ok(this)
616 }
617
618 /// Serialize the buffer's state to a protobuf message.
619 pub fn to_proto(&self, cx: &AppContext) -> proto::BufferState {
620 proto::BufferState {
621 id: self.remote_id().into(),
622 file: self.file.as_ref().map(|f| f.to_proto(cx)),
623 base_text: self.base_text().to_string(),
624 diff_base: self.diff_base.as_ref().map(|h| h.to_string()),
625 line_ending: proto::serialize_line_ending(self.line_ending()) as i32,
626 saved_version: proto::serialize_version(&self.saved_version),
627 saved_mtime: self.saved_mtime.map(|time| time.into()),
628 }
629 }
630
631 /// Serialize as protobufs all of the changes to the buffer since the given version.
632 pub fn serialize_ops(
633 &self,
634 since: Option<clock::Global>,
635 cx: &AppContext,
636 ) -> Task<Vec<proto::Operation>> {
637 let mut operations = Vec::new();
638 operations.extend(self.deferred_ops.iter().map(proto::serialize_operation));
639
640 operations.extend(self.remote_selections.iter().map(|(_, set)| {
641 proto::serialize_operation(&Operation::UpdateSelections {
642 selections: set.selections.clone(),
643 lamport_timestamp: set.lamport_timestamp,
644 line_mode: set.line_mode,
645 cursor_shape: set.cursor_shape,
646 })
647 }));
648
649 for (server_id, diagnostics) in &self.diagnostics {
650 operations.push(proto::serialize_operation(&Operation::UpdateDiagnostics {
651 lamport_timestamp: self.diagnostics_timestamp,
652 server_id: *server_id,
653 diagnostics: diagnostics.iter().cloned().collect(),
654 }));
655 }
656
657 operations.push(proto::serialize_operation(
658 &Operation::UpdateCompletionTriggers {
659 triggers: self.completion_triggers.clone(),
660 lamport_timestamp: self.completion_triggers_timestamp,
661 },
662 ));
663
664 let text_operations = self.text.operations().clone();
665 cx.background_executor().spawn(async move {
666 let since = since.unwrap_or_default();
667 operations.extend(
668 text_operations
669 .iter()
670 .filter(|(_, op)| !since.observed(op.timestamp()))
671 .map(|(_, op)| proto::serialize_operation(&Operation::Buffer(op.clone()))),
672 );
673 operations.sort_unstable_by_key(proto::lamport_timestamp_for_operation);
674 operations
675 })
676 }
677
678 /// Assign a language to the buffer, returning the buffer.
679 pub fn with_language(mut self, language: Arc<Language>, cx: &mut ModelContext<Self>) -> Self {
680 self.set_language(Some(language), cx);
681 self
682 }
683
684 /// Returns the [Capability] of this buffer.
685 pub fn capability(&self) -> Capability {
686 self.capability
687 }
688
689 /// Whether this buffer can only be read.
690 pub fn read_only(&self) -> bool {
691 self.capability == Capability::ReadOnly
692 }
693
694 /// Builds a [Buffer] with the given underlying [TextBuffer], diff base, [File] and [Capability].
695 pub fn build(
696 buffer: TextBuffer,
697 diff_base: Option<String>,
698 file: Option<Arc<dyn File>>,
699 capability: Capability,
700 ) -> Self {
701 let saved_mtime = file.as_ref().and_then(|file| file.mtime());
702
703 Self {
704 saved_mtime,
705 saved_version: buffer.version(),
706 reload_task: None,
707 transaction_depth: 0,
708 was_dirty_before_starting_transaction: None,
709 has_unsaved_edits: Cell::new((buffer.version(), false)),
710 text: buffer,
711 diff_base: diff_base
712 .map(|mut raw_diff_base| {
713 LineEnding::normalize(&mut raw_diff_base);
714 raw_diff_base
715 })
716 .map(Rope::from),
717 diff_base_version: 0,
718 git_diff: git::diff::BufferDiff::new(),
719 file,
720 capability,
721 syntax_map: Mutex::new(SyntaxMap::new()),
722 parsing_in_background: false,
723 non_text_state_update_count: 0,
724 sync_parse_timeout: Duration::from_millis(1),
725 parse_status: async_watch::channel(ParseStatus::Idle),
726 autoindent_requests: Default::default(),
727 pending_autoindent: Default::default(),
728 language: None,
729 remote_selections: Default::default(),
730 diagnostics: Default::default(),
731 diagnostics_timestamp: Default::default(),
732 completion_triggers: Default::default(),
733 completion_triggers_timestamp: Default::default(),
734 deferred_ops: OperationQueue::new(),
735 has_conflict: false,
736 }
737 }
738
739 /// Retrieve a snapshot of the buffer's current state. This is computationally
740 /// cheap, and allows reading from the buffer on a background thread.
741 pub fn snapshot(&self) -> BufferSnapshot {
742 let text = self.text.snapshot();
743 let mut syntax_map = self.syntax_map.lock();
744 syntax_map.interpolate(&text);
745 let syntax = syntax_map.snapshot();
746
747 BufferSnapshot {
748 text,
749 syntax,
750 git_diff: self.git_diff.clone(),
751 file: self.file.clone(),
752 remote_selections: self.remote_selections.clone(),
753 diagnostics: self.diagnostics.clone(),
754 language: self.language.clone(),
755 non_text_state_update_count: self.non_text_state_update_count,
756 }
757 }
758
759 #[cfg(test)]
760 pub(crate) fn as_text_snapshot(&self) -> &text::BufferSnapshot {
761 &self.text
762 }
763
764 /// Retrieve a snapshot of the buffer's raw text, without any
765 /// language-related state like the syntax tree or diagnostics.
766 pub fn text_snapshot(&self) -> text::BufferSnapshot {
767 self.text.snapshot()
768 }
769
770 /// The file associated with the buffer, if any.
771 pub fn file(&self) -> Option<&Arc<dyn File>> {
772 self.file.as_ref()
773 }
774
775 /// The version of the buffer that was last saved or reloaded from disk.
776 pub fn saved_version(&self) -> &clock::Global {
777 &self.saved_version
778 }
779
780 /// The mtime of the buffer's file when the buffer was last saved or reloaded from disk.
781 pub fn saved_mtime(&self) -> Option<SystemTime> {
782 self.saved_mtime
783 }
784
785 /// Assign a language to the buffer.
786 pub fn set_language(&mut self, language: Option<Arc<Language>>, cx: &mut ModelContext<Self>) {
787 self.non_text_state_update_count += 1;
788 self.syntax_map.lock().clear();
789 self.language = language;
790 self.reparse(cx);
791 cx.emit(Event::LanguageChanged);
792 }
793
794 /// Assign a language registry to the buffer. This allows the buffer to retrieve
795 /// other languages if parts of the buffer are written in different languages.
796 pub fn set_language_registry(&mut self, language_registry: Arc<LanguageRegistry>) {
797 self.syntax_map
798 .lock()
799 .set_language_registry(language_registry);
800 }
801
802 pub fn language_registry(&self) -> Option<Arc<LanguageRegistry>> {
803 self.syntax_map.lock().language_registry()
804 }
805
806 /// Assign the buffer a new [Capability].
807 pub fn set_capability(&mut self, capability: Capability, cx: &mut ModelContext<Self>) {
808 self.capability = capability;
809 cx.emit(Event::CapabilityChanged)
810 }
811
812 /// This method is called to signal that the buffer has been saved.
813 pub fn did_save(
814 &mut self,
815 version: clock::Global,
816 mtime: Option<SystemTime>,
817 cx: &mut ModelContext<Self>,
818 ) {
819 self.saved_version = version;
820 self.has_unsaved_edits
821 .set((self.saved_version().clone(), false));
822 self.has_conflict = false;
823 self.saved_mtime = mtime;
824 cx.emit(Event::Saved);
825 cx.notify();
826 }
827
828 /// Reloads the contents of the buffer from disk.
829 pub fn reload(
830 &mut self,
831 cx: &mut ModelContext<Self>,
832 ) -> oneshot::Receiver<Option<Transaction>> {
833 let (tx, rx) = futures::channel::oneshot::channel();
834 let prev_version = self.text.version();
835 self.reload_task = Some(cx.spawn(|this, mut cx| async move {
836 let Some((new_mtime, new_text)) = this.update(&mut cx, |this, cx| {
837 let file = this.file.as_ref()?.as_local()?;
838 Some((file.mtime(), file.load(cx)))
839 })?
840 else {
841 return Ok(());
842 };
843
844 let new_text = new_text.await?;
845 let diff = this
846 .update(&mut cx, |this, cx| this.diff(new_text.clone(), cx))?
847 .await;
848 this.update(&mut cx, |this, cx| {
849 if this.version() == diff.base_version {
850 this.finalize_last_transaction();
851 this.apply_diff(diff, cx);
852 tx.send(this.finalize_last_transaction().cloned()).ok();
853 this.has_conflict = false;
854 this.did_reload(this.version(), this.line_ending(), new_mtime, cx);
855 } else {
856 if !diff.edits.is_empty()
857 || this
858 .edits_since::<usize>(&diff.base_version)
859 .next()
860 .is_some()
861 {
862 this.has_conflict = true;
863 }
864
865 this.did_reload(prev_version, this.line_ending(), this.saved_mtime, cx);
866 }
867
868 this.reload_task.take();
869 })
870 }));
871 rx
872 }
873
874 /// This method is called to signal that the buffer has been reloaded.
875 pub fn did_reload(
876 &mut self,
877 version: clock::Global,
878 line_ending: LineEnding,
879 mtime: Option<SystemTime>,
880 cx: &mut ModelContext<Self>,
881 ) {
882 self.saved_version = version;
883 self.has_unsaved_edits
884 .set((self.saved_version.clone(), false));
885 self.text.set_line_ending(line_ending);
886 self.saved_mtime = mtime;
887 cx.emit(Event::Reloaded);
888 cx.notify();
889 }
890
891 /// Updates the [File] backing this buffer. This should be called when
892 /// the file has changed or has been deleted.
893 pub fn file_updated(&mut self, new_file: Arc<dyn File>, cx: &mut ModelContext<Self>) {
894 let mut file_changed = false;
895
896 if let Some(old_file) = self.file.as_ref() {
897 if new_file.path() != old_file.path() {
898 file_changed = true;
899 }
900
901 if new_file.is_deleted() {
902 if !old_file.is_deleted() {
903 file_changed = true;
904 if !self.is_dirty() {
905 cx.emit(Event::DirtyChanged);
906 }
907 }
908 } else {
909 let new_mtime = new_file.mtime();
910 if new_mtime != old_file.mtime() {
911 file_changed = true;
912
913 if !self.is_dirty() {
914 self.reload(cx).close();
915 }
916 }
917 }
918 } else {
919 file_changed = true;
920 };
921
922 self.file = Some(new_file);
923 if file_changed {
924 self.non_text_state_update_count += 1;
925 cx.emit(Event::FileHandleChanged);
926 cx.notify();
927 }
928 }
929
930 /// Returns the current diff base, see [Buffer::set_diff_base].
931 pub fn diff_base(&self) -> Option<&Rope> {
932 self.diff_base.as_ref()
933 }
934
935 /// Sets the text that will be used to compute a Git diff
936 /// against the buffer text.
937 pub fn set_diff_base(&mut self, diff_base: Option<String>, cx: &mut ModelContext<Self>) {
938 self.diff_base = diff_base
939 .map(|mut raw_diff_base| {
940 LineEnding::normalize(&mut raw_diff_base);
941 raw_diff_base
942 })
943 .map(Rope::from);
944 self.diff_base_version += 1;
945 if let Some(recalc_task) = self.git_diff_recalc(cx) {
946 cx.spawn(|buffer, mut cx| async move {
947 recalc_task.await;
948 buffer
949 .update(&mut cx, |_, cx| {
950 cx.emit(Event::DiffBaseChanged);
951 })
952 .ok();
953 })
954 .detach();
955 }
956 }
957
958 /// Returns a number, unique per diff base set to the buffer.
959 pub fn diff_base_version(&self) -> usize {
960 self.diff_base_version
961 }
962
963 /// Recomputes the Git diff status.
964 pub fn git_diff_recalc(&mut self, cx: &mut ModelContext<Self>) -> Option<Task<()>> {
965 let diff_base = self.diff_base.clone()?;
966 let snapshot = self.snapshot();
967
968 let mut diff = self.git_diff.clone();
969 let diff = cx.background_executor().spawn(async move {
970 diff.update(&diff_base, &snapshot).await;
971 diff
972 });
973
974 Some(cx.spawn(|this, mut cx| async move {
975 let buffer_diff = diff.await;
976 this.update(&mut cx, |this, cx| {
977 this.git_diff = buffer_diff;
978 this.non_text_state_update_count += 1;
979 cx.emit(Event::DiffUpdated);
980 })
981 .ok();
982 }))
983 }
984
985 /// Returns the primary [Language] assigned to this [Buffer].
986 pub fn language(&self) -> Option<&Arc<Language>> {
987 self.language.as_ref()
988 }
989
990 /// Returns the [Language] at the given location.
991 pub fn language_at<D: ToOffset>(&self, position: D) -> Option<Arc<Language>> {
992 let offset = position.to_offset(self);
993 self.syntax_map
994 .lock()
995 .layers_for_range(offset..offset, &self.text)
996 .last()
997 .map(|info| info.language.clone())
998 .or_else(|| self.language.clone())
999 }
1000
1001 /// An integer version number that accounts for all updates besides
1002 /// the buffer's text itself (which is versioned via a version vector).
1003 pub fn non_text_state_update_count(&self) -> usize {
1004 self.non_text_state_update_count
1005 }
1006
1007 /// Whether the buffer is being parsed in the background.
1008 #[cfg(any(test, feature = "test-support"))]
1009 pub fn is_parsing(&self) -> bool {
1010 self.parsing_in_background
1011 }
1012
1013 /// Indicates whether the buffer contains any regions that may be
1014 /// written in a language that hasn't been loaded yet.
1015 pub fn contains_unknown_injections(&self) -> bool {
1016 self.syntax_map.lock().contains_unknown_injections()
1017 }
1018
1019 #[cfg(test)]
1020 pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
1021 self.sync_parse_timeout = timeout;
1022 }
1023
1024 /// Called after an edit to synchronize the buffer's main parse tree with
1025 /// the buffer's new underlying state.
1026 ///
1027 /// Locks the syntax map and interpolates the edits since the last reparse
1028 /// into the foreground syntax tree.
1029 ///
1030 /// Then takes a stable snapshot of the syntax map before unlocking it.
1031 /// The snapshot with the interpolated edits is sent to a background thread,
1032 /// where we ask Tree-sitter to perform an incremental parse.
1033 ///
1034 /// Meanwhile, in the foreground, we block the main thread for up to 1ms
1035 /// waiting on the parse to complete. As soon as it completes, we proceed
1036 /// synchronously, unless a 1ms timeout elapses.
1037 ///
1038 /// If we time out waiting on the parse, we spawn a second task waiting
1039 /// until the parse does complete and return with the interpolated tree still
1040 /// in the foreground. When the background parse completes, call back into
1041 /// the main thread and assign the foreground parse state.
1042 ///
1043 /// If the buffer or grammar changed since the start of the background parse,
1044 /// initiate an additional reparse recursively. To avoid concurrent parses
1045 /// for the same buffer, we only initiate a new parse if we are not already
1046 /// parsing in the background.
1047 pub fn reparse(&mut self, cx: &mut ModelContext<Self>) {
1048 if self.parsing_in_background {
1049 return;
1050 }
1051 let language = if let Some(language) = self.language.clone() {
1052 language
1053 } else {
1054 return;
1055 };
1056
1057 let text = self.text_snapshot();
1058 let parsed_version = self.version();
1059
1060 let mut syntax_map = self.syntax_map.lock();
1061 syntax_map.interpolate(&text);
1062 let language_registry = syntax_map.language_registry();
1063 let mut syntax_snapshot = syntax_map.snapshot();
1064 drop(syntax_map);
1065
1066 let parse_task = cx.background_executor().spawn({
1067 let language = language.clone();
1068 let language_registry = language_registry.clone();
1069 async move {
1070 syntax_snapshot.reparse(&text, language_registry, language);
1071 syntax_snapshot
1072 }
1073 });
1074
1075 self.parse_status.0.send(ParseStatus::Parsing).unwrap();
1076 match cx
1077 .background_executor()
1078 .block_with_timeout(self.sync_parse_timeout, parse_task)
1079 {
1080 Ok(new_syntax_snapshot) => {
1081 self.did_finish_parsing(new_syntax_snapshot, cx);
1082 return;
1083 }
1084 Err(parse_task) => {
1085 self.parsing_in_background = true;
1086 cx.spawn(move |this, mut cx| async move {
1087 let new_syntax_map = parse_task.await;
1088 this.update(&mut cx, move |this, cx| {
1089 let grammar_changed =
1090 this.language.as_ref().map_or(true, |current_language| {
1091 !Arc::ptr_eq(&language, current_language)
1092 });
1093 let language_registry_changed = new_syntax_map
1094 .contains_unknown_injections()
1095 && language_registry.map_or(false, |registry| {
1096 registry.version() != new_syntax_map.language_registry_version()
1097 });
1098 let parse_again = language_registry_changed
1099 || grammar_changed
1100 || this.version.changed_since(&parsed_version);
1101 this.did_finish_parsing(new_syntax_map, cx);
1102 this.parsing_in_background = false;
1103 if parse_again {
1104 this.reparse(cx);
1105 }
1106 })
1107 .ok();
1108 })
1109 .detach();
1110 }
1111 }
1112 }
1113
1114 fn did_finish_parsing(&mut self, syntax_snapshot: SyntaxSnapshot, cx: &mut ModelContext<Self>) {
1115 self.non_text_state_update_count += 1;
1116 self.syntax_map.lock().did_parse(syntax_snapshot);
1117 self.request_autoindent(cx);
1118 self.parse_status.0.send(ParseStatus::Idle).unwrap();
1119 cx.emit(Event::Reparsed);
1120 cx.notify();
1121 }
1122
1123 pub fn parse_status(&self) -> watch::Receiver<ParseStatus> {
1124 self.parse_status.1.clone()
1125 }
1126
1127 /// Assign to the buffer a set of diagnostics created by a given language server.
1128 pub fn update_diagnostics(
1129 &mut self,
1130 server_id: LanguageServerId,
1131 diagnostics: DiagnosticSet,
1132 cx: &mut ModelContext<Self>,
1133 ) {
1134 let lamport_timestamp = self.text.lamport_clock.tick();
1135 let op = Operation::UpdateDiagnostics {
1136 server_id,
1137 diagnostics: diagnostics.iter().cloned().collect(),
1138 lamport_timestamp,
1139 };
1140 self.apply_diagnostic_update(server_id, diagnostics, lamport_timestamp, cx);
1141 self.send_operation(op, cx);
1142 }
1143
1144 fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
1145 if let Some(indent_sizes) = self.compute_autoindents() {
1146 let indent_sizes = cx.background_executor().spawn(indent_sizes);
1147 match cx
1148 .background_executor()
1149 .block_with_timeout(Duration::from_micros(500), indent_sizes)
1150 {
1151 Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
1152 Err(indent_sizes) => {
1153 self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
1154 let indent_sizes = indent_sizes.await;
1155 this.update(&mut cx, |this, cx| {
1156 this.apply_autoindents(indent_sizes, cx);
1157 })
1158 .ok();
1159 }));
1160 }
1161 }
1162 } else {
1163 self.autoindent_requests.clear();
1164 }
1165 }
1166
1167 fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>>> {
1168 let max_rows_between_yields = 100;
1169 let snapshot = self.snapshot();
1170 if snapshot.syntax.is_empty() || self.autoindent_requests.is_empty() {
1171 return None;
1172 }
1173
1174 let autoindent_requests = self.autoindent_requests.clone();
1175 Some(async move {
1176 let mut indent_sizes = BTreeMap::new();
1177 for request in autoindent_requests {
1178 // Resolve each edited range to its row in the current buffer and in the
1179 // buffer before this batch of edits.
1180 let mut row_ranges = Vec::new();
1181 let mut old_to_new_rows = BTreeMap::new();
1182 let mut language_indent_sizes_by_new_row = Vec::new();
1183 for entry in &request.entries {
1184 let position = entry.range.start;
1185 let new_row = position.to_point(&snapshot).row;
1186 let new_end_row = entry.range.end.to_point(&snapshot).row + 1;
1187 language_indent_sizes_by_new_row.push((new_row, entry.indent_size));
1188
1189 if !entry.first_line_is_new {
1190 let old_row = position.to_point(&request.before_edit).row;
1191 old_to_new_rows.insert(old_row, new_row);
1192 }
1193 row_ranges.push((new_row..new_end_row, entry.original_indent_column));
1194 }
1195
1196 // Build a map containing the suggested indentation for each of the edited lines
1197 // with respect to the state of the buffer before these edits. This map is keyed
1198 // by the rows for these lines in the current state of the buffer.
1199 let mut old_suggestions = BTreeMap::<u32, (IndentSize, bool)>::default();
1200 let old_edited_ranges =
1201 contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
1202 let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1203 let mut language_indent_size = IndentSize::default();
1204 for old_edited_range in old_edited_ranges {
1205 let suggestions = request
1206 .before_edit
1207 .suggest_autoindents(old_edited_range.clone())
1208 .into_iter()
1209 .flatten();
1210 for (old_row, suggestion) in old_edited_range.zip(suggestions) {
1211 if let Some(suggestion) = suggestion {
1212 let new_row = *old_to_new_rows.get(&old_row).unwrap();
1213
1214 // Find the indent size based on the language for this row.
1215 while let Some((row, size)) = language_indent_sizes.peek() {
1216 if *row > new_row {
1217 break;
1218 }
1219 language_indent_size = *size;
1220 language_indent_sizes.next();
1221 }
1222
1223 let suggested_indent = old_to_new_rows
1224 .get(&suggestion.basis_row)
1225 .and_then(|from_row| {
1226 Some(old_suggestions.get(from_row).copied()?.0)
1227 })
1228 .unwrap_or_else(|| {
1229 request
1230 .before_edit
1231 .indent_size_for_line(suggestion.basis_row)
1232 })
1233 .with_delta(suggestion.delta, language_indent_size);
1234 old_suggestions
1235 .insert(new_row, (suggested_indent, suggestion.within_error));
1236 }
1237 }
1238 yield_now().await;
1239 }
1240
1241 // In block mode, only compute indentation suggestions for the first line
1242 // of each insertion. Otherwise, compute suggestions for every inserted line.
1243 let new_edited_row_ranges = contiguous_ranges(
1244 row_ranges.iter().flat_map(|(range, _)| {
1245 if request.is_block_mode {
1246 range.start..range.start + 1
1247 } else {
1248 range.clone()
1249 }
1250 }),
1251 max_rows_between_yields,
1252 );
1253
1254 // Compute new suggestions for each line, but only include them in the result
1255 // if they differ from the old suggestion for that line.
1256 let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
1257 let mut language_indent_size = IndentSize::default();
1258 for new_edited_row_range in new_edited_row_ranges {
1259 let suggestions = snapshot
1260 .suggest_autoindents(new_edited_row_range.clone())
1261 .into_iter()
1262 .flatten();
1263 for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
1264 if let Some(suggestion) = suggestion {
1265 // Find the indent size based on the language for this row.
1266 while let Some((row, size)) = language_indent_sizes.peek() {
1267 if *row > new_row {
1268 break;
1269 }
1270 language_indent_size = *size;
1271 language_indent_sizes.next();
1272 }
1273
1274 let suggested_indent = indent_sizes
1275 .get(&suggestion.basis_row)
1276 .copied()
1277 .unwrap_or_else(|| {
1278 snapshot.indent_size_for_line(suggestion.basis_row)
1279 })
1280 .with_delta(suggestion.delta, language_indent_size);
1281 if old_suggestions.get(&new_row).map_or(
1282 true,
1283 |(old_indentation, was_within_error)| {
1284 suggested_indent != *old_indentation
1285 && (!suggestion.within_error || *was_within_error)
1286 },
1287 ) {
1288 indent_sizes.insert(new_row, suggested_indent);
1289 }
1290 }
1291 }
1292 yield_now().await;
1293 }
1294
1295 // For each block of inserted text, adjust the indentation of the remaining
1296 // lines of the block by the same amount as the first line was adjusted.
1297 if request.is_block_mode {
1298 for (row_range, original_indent_column) in
1299 row_ranges
1300 .into_iter()
1301 .filter_map(|(range, original_indent_column)| {
1302 if range.len() > 1 {
1303 Some((range, original_indent_column?))
1304 } else {
1305 None
1306 }
1307 })
1308 {
1309 let new_indent = indent_sizes
1310 .get(&row_range.start)
1311 .copied()
1312 .unwrap_or_else(|| snapshot.indent_size_for_line(row_range.start));
1313 let delta = new_indent.len as i64 - original_indent_column as i64;
1314 if delta != 0 {
1315 for row in row_range.skip(1) {
1316 indent_sizes.entry(row).or_insert_with(|| {
1317 let mut size = snapshot.indent_size_for_line(row);
1318 if size.kind == new_indent.kind {
1319 match delta.cmp(&0) {
1320 Ordering::Greater => size.len += delta as u32,
1321 Ordering::Less => {
1322 size.len = size.len.saturating_sub(-delta as u32)
1323 }
1324 Ordering::Equal => {}
1325 }
1326 }
1327 size
1328 });
1329 }
1330 }
1331 }
1332 }
1333 }
1334
1335 indent_sizes
1336 })
1337 }
1338
1339 fn apply_autoindents(
1340 &mut self,
1341 indent_sizes: BTreeMap<u32, IndentSize>,
1342 cx: &mut ModelContext<Self>,
1343 ) {
1344 self.autoindent_requests.clear();
1345
1346 let edits: Vec<_> = indent_sizes
1347 .into_iter()
1348 .filter_map(|(row, indent_size)| {
1349 let current_size = indent_size_for_line(self, row);
1350 Self::edit_for_indent_size_adjustment(row, current_size, indent_size)
1351 })
1352 .collect();
1353
1354 self.edit(edits, None, cx);
1355 }
1356
1357 /// Create a minimal edit that will cause the given row to be indented
1358 /// with the given size. After applying this edit, the length of the line
1359 /// will always be at least `new_size.len`.
1360 pub fn edit_for_indent_size_adjustment(
1361 row: u32,
1362 current_size: IndentSize,
1363 new_size: IndentSize,
1364 ) -> Option<(Range<Point>, String)> {
1365 if new_size.kind == current_size.kind {
1366 match new_size.len.cmp(¤t_size.len) {
1367 Ordering::Greater => {
1368 let point = Point::new(row, 0);
1369 Some((
1370 point..point,
1371 iter::repeat(new_size.char())
1372 .take((new_size.len - current_size.len) as usize)
1373 .collect::<String>(),
1374 ))
1375 }
1376
1377 Ordering::Less => Some((
1378 Point::new(row, 0)..Point::new(row, current_size.len - new_size.len),
1379 String::new(),
1380 )),
1381
1382 Ordering::Equal => None,
1383 }
1384 } else {
1385 Some((
1386 Point::new(row, 0)..Point::new(row, current_size.len),
1387 iter::repeat(new_size.char())
1388 .take(new_size.len as usize)
1389 .collect::<String>(),
1390 ))
1391 }
1392 }
1393
1394 /// Spawns a background task that asynchronously computes a `Diff` between the buffer's text
1395 /// and the given new text.
1396 pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
1397 let old_text = self.as_rope().clone();
1398 let base_version = self.version();
1399 cx.background_executor()
1400 .spawn_labeled(*BUFFER_DIFF_TASK, async move {
1401 let old_text = old_text.to_string();
1402 let line_ending = LineEnding::detect(&new_text);
1403 LineEnding::normalize(&mut new_text);
1404
1405 let diff = TextDiff::from_chars(old_text.as_str(), new_text.as_str());
1406 let empty: Arc<str> = Arc::default();
1407
1408 let mut edits = Vec::new();
1409 let mut old_offset = 0;
1410 let mut new_offset = 0;
1411 let mut last_edit: Option<(Range<usize>, Range<usize>)> = None;
1412 for change in diff.iter_all_changes().map(Some).chain([None]) {
1413 if let Some(change) = &change {
1414 let len = change.value().len();
1415 match change.tag() {
1416 ChangeTag::Equal => {
1417 old_offset += len;
1418 new_offset += len;
1419 }
1420 ChangeTag::Delete => {
1421 let old_end_offset = old_offset + len;
1422 if let Some((last_old_range, _)) = &mut last_edit {
1423 last_old_range.end = old_end_offset;
1424 } else {
1425 last_edit =
1426 Some((old_offset..old_end_offset, new_offset..new_offset));
1427 }
1428 old_offset = old_end_offset;
1429 }
1430 ChangeTag::Insert => {
1431 let new_end_offset = new_offset + len;
1432 if let Some((_, last_new_range)) = &mut last_edit {
1433 last_new_range.end = new_end_offset;
1434 } else {
1435 last_edit =
1436 Some((old_offset..old_offset, new_offset..new_end_offset));
1437 }
1438 new_offset = new_end_offset;
1439 }
1440 }
1441 }
1442
1443 if let Some((old_range, new_range)) = &last_edit {
1444 if old_offset > old_range.end
1445 || new_offset > new_range.end
1446 || change.is_none()
1447 {
1448 let text = if new_range.is_empty() {
1449 empty.clone()
1450 } else {
1451 new_text[new_range.clone()].into()
1452 };
1453 edits.push((old_range.clone(), text));
1454 last_edit.take();
1455 }
1456 }
1457 }
1458
1459 Diff {
1460 base_version,
1461 line_ending,
1462 edits,
1463 }
1464 })
1465 }
1466
1467 /// Spawns a background task that searches the buffer for any whitespace
1468 /// at the ends of a lines, and returns a `Diff` that removes that whitespace.
1469 pub fn remove_trailing_whitespace(&self, cx: &AppContext) -> Task<Diff> {
1470 let old_text = self.as_rope().clone();
1471 let line_ending = self.line_ending();
1472 let base_version = self.version();
1473 cx.background_executor().spawn(async move {
1474 let ranges = trailing_whitespace_ranges(&old_text);
1475 let empty = Arc::<str>::from("");
1476 Diff {
1477 base_version,
1478 line_ending,
1479 edits: ranges
1480 .into_iter()
1481 .map(|range| (range, empty.clone()))
1482 .collect(),
1483 }
1484 })
1485 }
1486
1487 /// Ensures that the buffer ends with a single newline character, and
1488 /// no other whitespace.
1489 pub fn ensure_final_newline(&mut self, cx: &mut ModelContext<Self>) {
1490 let len = self.len();
1491 let mut offset = len;
1492 for chunk in self.as_rope().reversed_chunks_in_range(0..len) {
1493 let non_whitespace_len = chunk
1494 .trim_end_matches(|c: char| c.is_ascii_whitespace())
1495 .len();
1496 offset -= chunk.len();
1497 offset += non_whitespace_len;
1498 if non_whitespace_len != 0 {
1499 if offset == len - 1 && chunk.get(non_whitespace_len..) == Some("\n") {
1500 return;
1501 }
1502 break;
1503 }
1504 }
1505 self.edit([(offset..len, "\n")], None, cx);
1506 }
1507
1508 /// Applies a diff to the buffer. If the buffer has changed since the given diff was
1509 /// calculated, then adjust the diff to account for those changes, and discard any
1510 /// parts of the diff that conflict with those changes.
1511 pub fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1512 // Check for any edits to the buffer that have occurred since this diff
1513 // was computed.
1514 let snapshot = self.snapshot();
1515 let mut edits_since = snapshot.edits_since::<usize>(&diff.base_version).peekable();
1516 let mut delta = 0;
1517 let adjusted_edits = diff.edits.into_iter().filter_map(|(range, new_text)| {
1518 while let Some(edit_since) = edits_since.peek() {
1519 // If the edit occurs after a diff hunk, then it does not
1520 // affect that hunk.
1521 if edit_since.old.start > range.end {
1522 break;
1523 }
1524 // If the edit precedes the diff hunk, then adjust the hunk
1525 // to reflect the edit.
1526 else if edit_since.old.end < range.start {
1527 delta += edit_since.new_len() as i64 - edit_since.old_len() as i64;
1528 edits_since.next();
1529 }
1530 // If the edit intersects a diff hunk, then discard that hunk.
1531 else {
1532 return None;
1533 }
1534 }
1535
1536 let start = (range.start as i64 + delta) as usize;
1537 let end = (range.end as i64 + delta) as usize;
1538 Some((start..end, new_text))
1539 });
1540
1541 self.start_transaction();
1542 self.text.set_line_ending(diff.line_ending);
1543 self.edit(adjusted_edits, None, cx);
1544 self.end_transaction(cx)
1545 }
1546
1547 fn has_unsaved_edits(&self) -> bool {
1548 let (last_version, has_unsaved_edits) = self.has_unsaved_edits.take();
1549
1550 if last_version == self.version {
1551 self.has_unsaved_edits
1552 .set((last_version, has_unsaved_edits));
1553 return has_unsaved_edits;
1554 }
1555
1556 let has_edits = self.has_edits_since(&self.saved_version);
1557 self.has_unsaved_edits
1558 .set((self.version.clone(), has_edits));
1559 has_edits
1560 }
1561
1562 /// Checks if the buffer has unsaved changes.
1563 pub fn is_dirty(&self) -> bool {
1564 self.has_conflict
1565 || self.has_unsaved_edits()
1566 || self
1567 .file
1568 .as_ref()
1569 .map_or(false, |file| file.is_deleted() || !file.is_created())
1570 }
1571
1572 /// Checks if the buffer and its file have both changed since the buffer
1573 /// was last saved or reloaded.
1574 pub fn has_conflict(&self) -> bool {
1575 self.has_conflict
1576 || self.file.as_ref().map_or(false, |file| {
1577 file.mtime() > self.saved_mtime && self.has_unsaved_edits()
1578 })
1579 }
1580
1581 /// Gets a [`Subscription`] that tracks all of the changes to the buffer's text.
1582 pub fn subscribe(&mut self) -> Subscription {
1583 self.text.subscribe()
1584 }
1585
1586 /// Starts a transaction, if one is not already in-progress. When undoing or
1587 /// redoing edits, all of the edits performed within a transaction are undone
1588 /// or redone together.
1589 pub fn start_transaction(&mut self) -> Option<TransactionId> {
1590 self.start_transaction_at(Instant::now())
1591 }
1592
1593 /// Starts a transaction, providing the current time. Subsequent transactions
1594 /// that occur within a short period of time will be grouped together. This
1595 /// is controlled by the buffer's undo grouping duration.
1596 pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1597 self.transaction_depth += 1;
1598 if self.was_dirty_before_starting_transaction.is_none() {
1599 self.was_dirty_before_starting_transaction = Some(self.is_dirty());
1600 }
1601 self.text.start_transaction_at(now)
1602 }
1603
1604 /// Terminates the current transaction, if this is the outermost transaction.
1605 pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1606 self.end_transaction_at(Instant::now(), cx)
1607 }
1608
1609 /// Terminates the current transaction, providing the current time. Subsequent transactions
1610 /// that occur within a short period of time will be grouped together. This
1611 /// is controlled by the buffer's undo grouping duration.
1612 pub fn end_transaction_at(
1613 &mut self,
1614 now: Instant,
1615 cx: &mut ModelContext<Self>,
1616 ) -> Option<TransactionId> {
1617 assert!(self.transaction_depth > 0);
1618 self.transaction_depth -= 1;
1619 let was_dirty = if self.transaction_depth == 0 {
1620 self.was_dirty_before_starting_transaction.take().unwrap()
1621 } else {
1622 false
1623 };
1624 if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1625 self.did_edit(&start_version, was_dirty, cx);
1626 Some(transaction_id)
1627 } else {
1628 None
1629 }
1630 }
1631
1632 /// Manually add a transaction to the buffer's undo history.
1633 pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1634 self.text.push_transaction(transaction, now);
1635 }
1636
1637 /// Prevent the last transaction from being grouped with any subsequent transactions,
1638 /// even if they occur with the buffer's undo grouping duration.
1639 pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1640 self.text.finalize_last_transaction()
1641 }
1642
1643 /// Manually group all changes since a given transaction.
1644 pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
1645 self.text.group_until_transaction(transaction_id);
1646 }
1647
1648 /// Manually remove a transaction from the buffer's undo history
1649 pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1650 self.text.forget_transaction(transaction_id);
1651 }
1652
1653 /// Manually merge two adjacent transactions in the buffer's undo history.
1654 pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
1655 self.text.merge_transactions(transaction, destination);
1656 }
1657
1658 /// Waits for the buffer to receive operations with the given timestamps.
1659 pub fn wait_for_edits(
1660 &mut self,
1661 edit_ids: impl IntoIterator<Item = clock::Lamport>,
1662 ) -> impl Future<Output = Result<()>> {
1663 self.text.wait_for_edits(edit_ids)
1664 }
1665
1666 /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
1667 pub fn wait_for_anchors(
1668 &mut self,
1669 anchors: impl IntoIterator<Item = Anchor>,
1670 ) -> impl 'static + Future<Output = Result<()>> {
1671 self.text.wait_for_anchors(anchors)
1672 }
1673
1674 /// Waits for the buffer to receive operations up to the given version.
1675 pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
1676 self.text.wait_for_version(version)
1677 }
1678
1679 /// Forces all futures returned by [`Buffer::wait_for_version`], [`Buffer::wait_for_edits`], or
1680 /// [`Buffer::wait_for_version`] to resolve with an error.
1681 pub fn give_up_waiting(&mut self) {
1682 self.text.give_up_waiting();
1683 }
1684
1685 /// Stores a set of selections that should be broadcasted to all of the buffer's replicas.
1686 pub fn set_active_selections(
1687 &mut self,
1688 selections: Arc<[Selection<Anchor>]>,
1689 line_mode: bool,
1690 cursor_shape: CursorShape,
1691 cx: &mut ModelContext<Self>,
1692 ) {
1693 let lamport_timestamp = self.text.lamport_clock.tick();
1694 self.remote_selections.insert(
1695 self.text.replica_id(),
1696 SelectionSet {
1697 selections: selections.clone(),
1698 lamport_timestamp,
1699 line_mode,
1700 cursor_shape,
1701 },
1702 );
1703 self.send_operation(
1704 Operation::UpdateSelections {
1705 selections,
1706 line_mode,
1707 lamport_timestamp,
1708 cursor_shape,
1709 },
1710 cx,
1711 );
1712 self.non_text_state_update_count += 1;
1713 cx.notify();
1714 }
1715
1716 /// Clears the selections, so that other replicas of the buffer do not see any selections for
1717 /// this replica.
1718 pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1719 if self
1720 .remote_selections
1721 .get(&self.text.replica_id())
1722 .map_or(true, |set| !set.selections.is_empty())
1723 {
1724 self.set_active_selections(Arc::default(), false, Default::default(), cx);
1725 }
1726 }
1727
1728 /// Replaces the buffer's entire text.
1729 pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Lamport>
1730 where
1731 T: Into<Arc<str>>,
1732 {
1733 self.autoindent_requests.clear();
1734 self.edit([(0..self.len(), text)], None, cx)
1735 }
1736
1737 /// Applies the given edits to the buffer. Each edit is specified as a range of text to
1738 /// delete, and a string of text to insert at that location.
1739 ///
1740 /// If an [`AutoindentMode`] is provided, then the buffer will enqueue an auto-indent
1741 /// request for the edited ranges, which will be processed when the buffer finishes
1742 /// parsing.
1743 ///
1744 /// Parsing takes place at the end of a transaction, and may compute synchronously
1745 /// or asynchronously, depending on the changes.
1746 pub fn edit<I, S, T>(
1747 &mut self,
1748 edits_iter: I,
1749 autoindent_mode: Option<AutoindentMode>,
1750 cx: &mut ModelContext<Self>,
1751 ) -> Option<clock::Lamport>
1752 where
1753 I: IntoIterator<Item = (Range<S>, T)>,
1754 S: ToOffset,
1755 T: Into<Arc<str>>,
1756 {
1757 // Skip invalid edits and coalesce contiguous ones.
1758 let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1759 for (range, new_text) in edits_iter {
1760 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1761 if range.start > range.end {
1762 mem::swap(&mut range.start, &mut range.end);
1763 }
1764 let new_text = new_text.into();
1765 if !new_text.is_empty() || !range.is_empty() {
1766 if let Some((prev_range, prev_text)) = edits.last_mut() {
1767 if prev_range.end >= range.start {
1768 prev_range.end = cmp::max(prev_range.end, range.end);
1769 *prev_text = format!("{prev_text}{new_text}").into();
1770 } else {
1771 edits.push((range, new_text));
1772 }
1773 } else {
1774 edits.push((range, new_text));
1775 }
1776 }
1777 }
1778 if edits.is_empty() {
1779 return None;
1780 }
1781
1782 self.start_transaction();
1783 self.pending_autoindent.take();
1784 let autoindent_request = autoindent_mode
1785 .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
1786
1787 let edit_operation = self.text.edit(edits.iter().cloned());
1788 let edit_id = edit_operation.timestamp();
1789
1790 if let Some((before_edit, mode)) = autoindent_request {
1791 let mut delta = 0isize;
1792 let entries = edits
1793 .into_iter()
1794 .enumerate()
1795 .zip(&edit_operation.as_edit().unwrap().new_text)
1796 .map(|((ix, (range, _)), new_text)| {
1797 let new_text_length = new_text.len();
1798 let old_start = range.start.to_point(&before_edit);
1799 let new_start = (delta + range.start as isize) as usize;
1800 delta += new_text_length as isize - (range.end as isize - range.start as isize);
1801
1802 let mut range_of_insertion_to_indent = 0..new_text_length;
1803 let mut first_line_is_new = false;
1804 let mut original_indent_column = None;
1805
1806 // When inserting an entire line at the beginning of an existing line,
1807 // treat the insertion as new.
1808 if new_text.contains('\n')
1809 && old_start.column <= before_edit.indent_size_for_line(old_start.row).len
1810 {
1811 first_line_is_new = true;
1812 }
1813
1814 // When inserting text starting with a newline, avoid auto-indenting the
1815 // previous line.
1816 if new_text.starts_with('\n') {
1817 range_of_insertion_to_indent.start += 1;
1818 first_line_is_new = true;
1819 }
1820
1821 // Avoid auto-indenting after the insertion.
1822 if let AutoindentMode::Block {
1823 original_indent_columns,
1824 } = &mode
1825 {
1826 original_indent_column =
1827 Some(original_indent_columns.get(ix).copied().unwrap_or_else(|| {
1828 indent_size_for_text(
1829 new_text[range_of_insertion_to_indent.clone()].chars(),
1830 )
1831 .len
1832 }));
1833 if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
1834 range_of_insertion_to_indent.end -= 1;
1835 }
1836 }
1837
1838 AutoindentRequestEntry {
1839 first_line_is_new,
1840 original_indent_column,
1841 indent_size: before_edit.language_indent_size_at(range.start, cx),
1842 range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
1843 ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
1844 }
1845 })
1846 .collect();
1847
1848 self.autoindent_requests.push(Arc::new(AutoindentRequest {
1849 before_edit,
1850 entries,
1851 is_block_mode: matches!(mode, AutoindentMode::Block { .. }),
1852 }));
1853 }
1854
1855 self.end_transaction(cx);
1856 self.send_operation(Operation::Buffer(edit_operation), cx);
1857 Some(edit_id)
1858 }
1859
1860 fn did_edit(
1861 &mut self,
1862 old_version: &clock::Global,
1863 was_dirty: bool,
1864 cx: &mut ModelContext<Self>,
1865 ) {
1866 if self.edits_since::<usize>(old_version).next().is_none() {
1867 return;
1868 }
1869
1870 self.reparse(cx);
1871
1872 cx.emit(Event::Edited);
1873 if was_dirty != self.is_dirty() {
1874 cx.emit(Event::DirtyChanged);
1875 }
1876 cx.notify();
1877 }
1878
1879 /// Applies the given remote operations to the buffer.
1880 pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1881 &mut self,
1882 ops: I,
1883 cx: &mut ModelContext<Self>,
1884 ) -> Result<()> {
1885 self.pending_autoindent.take();
1886 let was_dirty = self.is_dirty();
1887 let old_version = self.version.clone();
1888 let mut deferred_ops = Vec::new();
1889 let buffer_ops = ops
1890 .into_iter()
1891 .filter_map(|op| match op {
1892 Operation::Buffer(op) => Some(op),
1893 _ => {
1894 if self.can_apply_op(&op) {
1895 self.apply_op(op, cx);
1896 } else {
1897 deferred_ops.push(op);
1898 }
1899 None
1900 }
1901 })
1902 .collect::<Vec<_>>();
1903 self.text.apply_ops(buffer_ops)?;
1904 self.deferred_ops.insert(deferred_ops);
1905 self.flush_deferred_ops(cx);
1906 self.did_edit(&old_version, was_dirty, cx);
1907 // Notify independently of whether the buffer was edited as the operations could include a
1908 // selection update.
1909 cx.notify();
1910 Ok(())
1911 }
1912
1913 fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1914 let mut deferred_ops = Vec::new();
1915 for op in self.deferred_ops.drain().iter().cloned() {
1916 if self.can_apply_op(&op) {
1917 self.apply_op(op, cx);
1918 } else {
1919 deferred_ops.push(op);
1920 }
1921 }
1922 self.deferred_ops.insert(deferred_ops);
1923 }
1924
1925 pub fn has_deferred_ops(&self) -> bool {
1926 !self.deferred_ops.is_empty() || self.text.has_deferred_ops()
1927 }
1928
1929 fn can_apply_op(&self, operation: &Operation) -> bool {
1930 match operation {
1931 Operation::Buffer(_) => {
1932 unreachable!("buffer operations should never be applied at this layer")
1933 }
1934 Operation::UpdateDiagnostics {
1935 diagnostics: diagnostic_set,
1936 ..
1937 } => diagnostic_set.iter().all(|diagnostic| {
1938 self.text.can_resolve(&diagnostic.range.start)
1939 && self.text.can_resolve(&diagnostic.range.end)
1940 }),
1941 Operation::UpdateSelections { selections, .. } => selections
1942 .iter()
1943 .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1944 Operation::UpdateCompletionTriggers { .. } => true,
1945 }
1946 }
1947
1948 fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1949 match operation {
1950 Operation::Buffer(_) => {
1951 unreachable!("buffer operations should never be applied at this layer")
1952 }
1953 Operation::UpdateDiagnostics {
1954 server_id,
1955 diagnostics: diagnostic_set,
1956 lamport_timestamp,
1957 } => {
1958 let snapshot = self.snapshot();
1959 self.apply_diagnostic_update(
1960 server_id,
1961 DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1962 lamport_timestamp,
1963 cx,
1964 );
1965 }
1966 Operation::UpdateSelections {
1967 selections,
1968 lamport_timestamp,
1969 line_mode,
1970 cursor_shape,
1971 } => {
1972 if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
1973 if set.lamport_timestamp > lamport_timestamp {
1974 return;
1975 }
1976 }
1977
1978 self.remote_selections.insert(
1979 lamport_timestamp.replica_id,
1980 SelectionSet {
1981 selections,
1982 lamport_timestamp,
1983 line_mode,
1984 cursor_shape,
1985 },
1986 );
1987 self.text.lamport_clock.observe(lamport_timestamp);
1988 self.non_text_state_update_count += 1;
1989 }
1990 Operation::UpdateCompletionTriggers {
1991 triggers,
1992 lamport_timestamp,
1993 } => {
1994 self.completion_triggers = triggers;
1995 self.text.lamport_clock.observe(lamport_timestamp);
1996 }
1997 }
1998 }
1999
2000 fn apply_diagnostic_update(
2001 &mut self,
2002 server_id: LanguageServerId,
2003 diagnostics: DiagnosticSet,
2004 lamport_timestamp: clock::Lamport,
2005 cx: &mut ModelContext<Self>,
2006 ) {
2007 if lamport_timestamp > self.diagnostics_timestamp {
2008 let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
2009 if diagnostics.len() == 0 {
2010 if let Ok(ix) = ix {
2011 self.diagnostics.remove(ix);
2012 }
2013 } else {
2014 match ix {
2015 Err(ix) => self.diagnostics.insert(ix, (server_id, diagnostics)),
2016 Ok(ix) => self.diagnostics[ix].1 = diagnostics,
2017 };
2018 }
2019 self.diagnostics_timestamp = lamport_timestamp;
2020 self.non_text_state_update_count += 1;
2021 self.text.lamport_clock.observe(lamport_timestamp);
2022 cx.notify();
2023 cx.emit(Event::DiagnosticsUpdated);
2024 }
2025 }
2026
2027 fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
2028 cx.emit(Event::Operation(operation));
2029 }
2030
2031 /// Removes the selections for a given peer.
2032 pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
2033 self.remote_selections.remove(&replica_id);
2034 cx.notify();
2035 }
2036
2037 /// Undoes the most recent transaction.
2038 pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
2039 let was_dirty = self.is_dirty();
2040 let old_version = self.version.clone();
2041
2042 if let Some((transaction_id, operation)) = self.text.undo() {
2043 self.send_operation(Operation::Buffer(operation), cx);
2044 self.did_edit(&old_version, was_dirty, cx);
2045 Some(transaction_id)
2046 } else {
2047 None
2048 }
2049 }
2050
2051 /// Manually undoes a specific transaction in the buffer's undo history.
2052 pub fn undo_transaction(
2053 &mut self,
2054 transaction_id: TransactionId,
2055 cx: &mut ModelContext<Self>,
2056 ) -> bool {
2057 let was_dirty = self.is_dirty();
2058 let old_version = self.version.clone();
2059 if let Some(operation) = self.text.undo_transaction(transaction_id) {
2060 self.send_operation(Operation::Buffer(operation), cx);
2061 self.did_edit(&old_version, was_dirty, cx);
2062 true
2063 } else {
2064 false
2065 }
2066 }
2067
2068 /// Manually undoes all changes after a given transaction in the buffer's undo history.
2069 pub fn undo_to_transaction(
2070 &mut self,
2071 transaction_id: TransactionId,
2072 cx: &mut ModelContext<Self>,
2073 ) -> bool {
2074 let was_dirty = self.is_dirty();
2075 let old_version = self.version.clone();
2076
2077 let operations = self.text.undo_to_transaction(transaction_id);
2078 let undone = !operations.is_empty();
2079 for operation in operations {
2080 self.send_operation(Operation::Buffer(operation), cx);
2081 }
2082 if undone {
2083 self.did_edit(&old_version, was_dirty, cx)
2084 }
2085 undone
2086 }
2087
2088 /// Manually redoes a specific transaction in the buffer's redo history.
2089 pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
2090 let was_dirty = self.is_dirty();
2091 let old_version = self.version.clone();
2092
2093 if let Some((transaction_id, operation)) = self.text.redo() {
2094 self.send_operation(Operation::Buffer(operation), cx);
2095 self.did_edit(&old_version, was_dirty, cx);
2096 Some(transaction_id)
2097 } else {
2098 None
2099 }
2100 }
2101
2102 /// Manually undoes all changes until a given transaction in the buffer's redo history.
2103 pub fn redo_to_transaction(
2104 &mut self,
2105 transaction_id: TransactionId,
2106 cx: &mut ModelContext<Self>,
2107 ) -> bool {
2108 let was_dirty = self.is_dirty();
2109 let old_version = self.version.clone();
2110
2111 let operations = self.text.redo_to_transaction(transaction_id);
2112 let redone = !operations.is_empty();
2113 for operation in operations {
2114 self.send_operation(Operation::Buffer(operation), cx);
2115 }
2116 if redone {
2117 self.did_edit(&old_version, was_dirty, cx)
2118 }
2119 redone
2120 }
2121
2122 /// Override current completion triggers with the user-provided completion triggers.
2123 pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
2124 self.completion_triggers.clone_from(&triggers);
2125 self.completion_triggers_timestamp = self.text.lamport_clock.tick();
2126 self.send_operation(
2127 Operation::UpdateCompletionTriggers {
2128 triggers,
2129 lamport_timestamp: self.completion_triggers_timestamp,
2130 },
2131 cx,
2132 );
2133 cx.notify();
2134 }
2135
2136 /// Returns a list of strings which trigger a completion menu for this language.
2137 /// Usually this is driven by LSP server which returns a list of trigger characters for completions.
2138 pub fn completion_triggers(&self) -> &[String] {
2139 &self.completion_triggers
2140 }
2141}
2142
2143#[doc(hidden)]
2144#[cfg(any(test, feature = "test-support"))]
2145impl Buffer {
2146 pub fn edit_via_marked_text(
2147 &mut self,
2148 marked_string: &str,
2149 autoindent_mode: Option<AutoindentMode>,
2150 cx: &mut ModelContext<Self>,
2151 ) {
2152 let edits = self.edits_for_marked_text(marked_string);
2153 self.edit(edits, autoindent_mode, cx);
2154 }
2155
2156 pub fn set_group_interval(&mut self, group_interval: Duration) {
2157 self.text.set_group_interval(group_interval);
2158 }
2159
2160 pub fn randomly_edit<T>(
2161 &mut self,
2162 rng: &mut T,
2163 old_range_count: usize,
2164 cx: &mut ModelContext<Self>,
2165 ) where
2166 T: rand::Rng,
2167 {
2168 let mut edits: Vec<(Range<usize>, String)> = Vec::new();
2169 let mut last_end = None;
2170 for _ in 0..old_range_count {
2171 if last_end.map_or(false, |last_end| last_end >= self.len()) {
2172 break;
2173 }
2174
2175 let new_start = last_end.map_or(0, |last_end| last_end + 1);
2176 let mut range = self.random_byte_range(new_start, rng);
2177 if rng.gen_bool(0.2) {
2178 mem::swap(&mut range.start, &mut range.end);
2179 }
2180 last_end = Some(range.end);
2181
2182 let new_text_len = rng.gen_range(0..10);
2183 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
2184
2185 edits.push((range, new_text));
2186 }
2187 log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
2188 self.edit(edits, None, cx);
2189 }
2190
2191 pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
2192 let was_dirty = self.is_dirty();
2193 let old_version = self.version.clone();
2194
2195 let ops = self.text.randomly_undo_redo(rng);
2196 if !ops.is_empty() {
2197 for op in ops {
2198 self.send_operation(Operation::Buffer(op), cx);
2199 self.did_edit(&old_version, was_dirty, cx);
2200 }
2201 }
2202 }
2203}
2204
2205impl EventEmitter<Event> for Buffer {}
2206
2207impl Deref for Buffer {
2208 type Target = TextBuffer;
2209
2210 fn deref(&self) -> &Self::Target {
2211 &self.text
2212 }
2213}
2214
2215impl BufferSnapshot {
2216 /// Returns [`IndentSize`] for a given line that respects user settings and /// language preferences.
2217 pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2218 indent_size_for_line(self, row)
2219 }
2220 /// Returns [`IndentSize`] for a given position that respects user settings
2221 /// and language preferences.
2222 pub fn language_indent_size_at<T: ToOffset>(&self, position: T, cx: &AppContext) -> IndentSize {
2223 let settings = language_settings(self.language_at(position), self.file(), cx);
2224 if settings.hard_tabs {
2225 IndentSize::tab()
2226 } else {
2227 IndentSize::spaces(settings.tab_size.get())
2228 }
2229 }
2230
2231 /// Retrieve the suggested indent size for all of the given rows. The unit of indentation
2232 /// is passed in as `single_indent_size`.
2233 pub fn suggested_indents(
2234 &self,
2235 rows: impl Iterator<Item = u32>,
2236 single_indent_size: IndentSize,
2237 ) -> BTreeMap<u32, IndentSize> {
2238 let mut result = BTreeMap::new();
2239
2240 for row_range in contiguous_ranges(rows, 10) {
2241 let suggestions = match self.suggest_autoindents(row_range.clone()) {
2242 Some(suggestions) => suggestions,
2243 _ => break,
2244 };
2245
2246 for (row, suggestion) in row_range.zip(suggestions) {
2247 let indent_size = if let Some(suggestion) = suggestion {
2248 result
2249 .get(&suggestion.basis_row)
2250 .copied()
2251 .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
2252 .with_delta(suggestion.delta, single_indent_size)
2253 } else {
2254 self.indent_size_for_line(row)
2255 };
2256
2257 result.insert(row, indent_size);
2258 }
2259 }
2260
2261 result
2262 }
2263
2264 fn suggest_autoindents(
2265 &self,
2266 row_range: Range<u32>,
2267 ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
2268 let config = &self.language.as_ref()?.config;
2269 let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
2270
2271 // Find the suggested indentation ranges based on the syntax tree.
2272 let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
2273 let end = Point::new(row_range.end, 0);
2274 let range = (start..end).to_offset(&self.text);
2275 let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2276 Some(&grammar.indents_config.as_ref()?.query)
2277 });
2278 let indent_configs = matches
2279 .grammars()
2280 .iter()
2281 .map(|grammar| grammar.indents_config.as_ref().unwrap())
2282 .collect::<Vec<_>>();
2283
2284 let mut indent_ranges = Vec::<Range<Point>>::new();
2285 let mut outdent_positions = Vec::<Point>::new();
2286 while let Some(mat) = matches.peek() {
2287 let mut start: Option<Point> = None;
2288 let mut end: Option<Point> = None;
2289
2290 let config = &indent_configs[mat.grammar_index];
2291 for capture in mat.captures {
2292 if capture.index == config.indent_capture_ix {
2293 start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
2294 end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
2295 } else if Some(capture.index) == config.start_capture_ix {
2296 start = Some(Point::from_ts_point(capture.node.end_position()));
2297 } else if Some(capture.index) == config.end_capture_ix {
2298 end = Some(Point::from_ts_point(capture.node.start_position()));
2299 } else if Some(capture.index) == config.outdent_capture_ix {
2300 outdent_positions.push(Point::from_ts_point(capture.node.start_position()));
2301 }
2302 }
2303
2304 matches.advance();
2305 if let Some((start, end)) = start.zip(end) {
2306 if start.row == end.row {
2307 continue;
2308 }
2309
2310 let range = start..end;
2311 match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
2312 Err(ix) => indent_ranges.insert(ix, range),
2313 Ok(ix) => {
2314 let prev_range = &mut indent_ranges[ix];
2315 prev_range.end = prev_range.end.max(range.end);
2316 }
2317 }
2318 }
2319 }
2320
2321 let mut error_ranges = Vec::<Range<Point>>::new();
2322 let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2323 Some(&grammar.error_query)
2324 });
2325 while let Some(mat) = matches.peek() {
2326 let node = mat.captures[0].node;
2327 let start = Point::from_ts_point(node.start_position());
2328 let end = Point::from_ts_point(node.end_position());
2329 let range = start..end;
2330 let ix = match error_ranges.binary_search_by_key(&range.start, |r| r.start) {
2331 Ok(ix) | Err(ix) => ix,
2332 };
2333 let mut end_ix = ix;
2334 while let Some(existing_range) = error_ranges.get(end_ix) {
2335 if existing_range.end < end {
2336 end_ix += 1;
2337 } else {
2338 break;
2339 }
2340 }
2341 error_ranges.splice(ix..end_ix, [range]);
2342 matches.advance();
2343 }
2344
2345 outdent_positions.sort();
2346 for outdent_position in outdent_positions {
2347 // find the innermost indent range containing this outdent_position
2348 // set its end to the outdent position
2349 if let Some(range_to_truncate) = indent_ranges
2350 .iter_mut()
2351 .filter(|indent_range| indent_range.contains(&outdent_position))
2352 .last()
2353 {
2354 range_to_truncate.end = outdent_position;
2355 }
2356 }
2357
2358 // Find the suggested indentation increases and decreased based on regexes.
2359 let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
2360 self.for_each_line(
2361 Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
2362 ..Point::new(row_range.end, 0),
2363 |row, line| {
2364 if config
2365 .decrease_indent_pattern
2366 .as_ref()
2367 .map_or(false, |regex| regex.is_match(line))
2368 {
2369 indent_change_rows.push((row, Ordering::Less));
2370 }
2371 if config
2372 .increase_indent_pattern
2373 .as_ref()
2374 .map_or(false, |regex| regex.is_match(line))
2375 {
2376 indent_change_rows.push((row + 1, Ordering::Greater));
2377 }
2378 },
2379 );
2380
2381 let mut indent_changes = indent_change_rows.into_iter().peekable();
2382 let mut prev_row = if config.auto_indent_using_last_non_empty_line {
2383 prev_non_blank_row.unwrap_or(0)
2384 } else {
2385 row_range.start.saturating_sub(1)
2386 };
2387 let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
2388 Some(row_range.map(move |row| {
2389 let row_start = Point::new(row, self.indent_size_for_line(row).len);
2390
2391 let mut indent_from_prev_row = false;
2392 let mut outdent_from_prev_row = false;
2393 let mut outdent_to_row = u32::MAX;
2394
2395 while let Some((indent_row, delta)) = indent_changes.peek() {
2396 match indent_row.cmp(&row) {
2397 Ordering::Equal => match delta {
2398 Ordering::Less => outdent_from_prev_row = true,
2399 Ordering::Greater => indent_from_prev_row = true,
2400 _ => {}
2401 },
2402
2403 Ordering::Greater => break,
2404 Ordering::Less => {}
2405 }
2406
2407 indent_changes.next();
2408 }
2409
2410 for range in &indent_ranges {
2411 if range.start.row >= row {
2412 break;
2413 }
2414 if range.start.row == prev_row && range.end > row_start {
2415 indent_from_prev_row = true;
2416 }
2417 if range.end > prev_row_start && range.end <= row_start {
2418 outdent_to_row = outdent_to_row.min(range.start.row);
2419 }
2420 }
2421
2422 let within_error = error_ranges
2423 .iter()
2424 .any(|e| e.start.row < row && e.end > row_start);
2425
2426 let suggestion = if outdent_to_row == prev_row
2427 || (outdent_from_prev_row && indent_from_prev_row)
2428 {
2429 Some(IndentSuggestion {
2430 basis_row: prev_row,
2431 delta: Ordering::Equal,
2432 within_error,
2433 })
2434 } else if indent_from_prev_row {
2435 Some(IndentSuggestion {
2436 basis_row: prev_row,
2437 delta: Ordering::Greater,
2438 within_error,
2439 })
2440 } else if outdent_to_row < prev_row {
2441 Some(IndentSuggestion {
2442 basis_row: outdent_to_row,
2443 delta: Ordering::Equal,
2444 within_error,
2445 })
2446 } else if outdent_from_prev_row {
2447 Some(IndentSuggestion {
2448 basis_row: prev_row,
2449 delta: Ordering::Less,
2450 within_error,
2451 })
2452 } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
2453 {
2454 Some(IndentSuggestion {
2455 basis_row: prev_row,
2456 delta: Ordering::Equal,
2457 within_error,
2458 })
2459 } else {
2460 None
2461 };
2462
2463 prev_row = row;
2464 prev_row_start = row_start;
2465 suggestion
2466 }))
2467 }
2468
2469 fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2470 while row > 0 {
2471 row -= 1;
2472 if !self.is_line_blank(row) {
2473 return Some(row);
2474 }
2475 }
2476 None
2477 }
2478
2479 fn get_highlights(&self, range: Range<usize>) -> (SyntaxMapCaptures, Vec<HighlightMap>) {
2480 let captures = self.syntax.captures(range, &self.text, |grammar| {
2481 grammar.highlights_query.as_ref()
2482 });
2483 let highlight_maps = captures
2484 .grammars()
2485 .into_iter()
2486 .map(|grammar| grammar.highlight_map())
2487 .collect();
2488 (captures, highlight_maps)
2489 }
2490 /// Iterates over chunks of text in the given range of the buffer. Text is chunked
2491 /// in an arbitrary way due to being stored in a [`Rope`](text::Rope). The text is also
2492 /// returned in chunks where each chunk has a single syntax highlighting style and
2493 /// diagnostic status.
2494 pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
2495 let range = range.start.to_offset(self)..range.end.to_offset(self);
2496
2497 let mut syntax = None;
2498 if language_aware {
2499 syntax = Some(self.get_highlights(range.clone()));
2500 }
2501
2502 BufferChunks::new(self.text.as_rope(), range, syntax, Some(self))
2503 }
2504
2505 /// Invokes the given callback for each line of text in the given range of the buffer.
2506 /// Uses callback to avoid allocating a string for each line.
2507 fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
2508 let mut line = String::new();
2509 let mut row = range.start.row;
2510 for chunk in self
2511 .as_rope()
2512 .chunks_in_range(range.to_offset(self))
2513 .chain(["\n"])
2514 {
2515 for (newline_ix, text) in chunk.split('\n').enumerate() {
2516 if newline_ix > 0 {
2517 callback(row, &line);
2518 row += 1;
2519 line.clear();
2520 }
2521 line.push_str(text);
2522 }
2523 }
2524 }
2525
2526 /// Iterates over every [`SyntaxLayer`] in the buffer.
2527 pub fn syntax_layers(&self) -> impl Iterator<Item = SyntaxLayer> + '_ {
2528 self.syntax.layers_for_range(0..self.len(), &self.text)
2529 }
2530
2531 pub fn syntax_layer_at<D: ToOffset>(&self, position: D) -> Option<SyntaxLayer> {
2532 let offset = position.to_offset(self);
2533 self.syntax
2534 .layers_for_range(offset..offset, &self.text)
2535 .filter(|l| l.node().end_byte() > offset)
2536 .last()
2537 }
2538
2539 /// Returns the main [Language]
2540 pub fn language(&self) -> Option<&Arc<Language>> {
2541 self.language.as_ref()
2542 }
2543
2544 /// Returns the [Language] at the given location.
2545 pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
2546 self.syntax_layer_at(position)
2547 .map(|info| info.language)
2548 .or(self.language.as_ref())
2549 }
2550
2551 /// Returns the settings for the language at the given location.
2552 pub fn settings_at<'a, D: ToOffset>(
2553 &self,
2554 position: D,
2555 cx: &'a AppContext,
2556 ) -> &'a LanguageSettings {
2557 language_settings(self.language_at(position), self.file.as_ref(), cx)
2558 }
2559
2560 /// Returns the [LanguageScope] at the given location.
2561 pub fn language_scope_at<D: ToOffset>(&self, position: D) -> Option<LanguageScope> {
2562 let offset = position.to_offset(self);
2563 let mut scope = None;
2564 let mut smallest_range: Option<Range<usize>> = None;
2565
2566 // Use the layer that has the smallest node intersecting the given point.
2567 for layer in self.syntax.layers_for_range(offset..offset, &self.text) {
2568 let mut cursor = layer.node().walk();
2569
2570 let mut range = None;
2571 loop {
2572 let child_range = cursor.node().byte_range();
2573 if !child_range.to_inclusive().contains(&offset) {
2574 break;
2575 }
2576
2577 range = Some(child_range);
2578 if cursor.goto_first_child_for_byte(offset).is_none() {
2579 break;
2580 }
2581 }
2582
2583 if let Some(range) = range {
2584 if smallest_range
2585 .as_ref()
2586 .map_or(true, |smallest_range| range.len() < smallest_range.len())
2587 {
2588 smallest_range = Some(range);
2589 scope = Some(LanguageScope {
2590 language: layer.language.clone(),
2591 override_id: layer.override_id(offset, &self.text),
2592 });
2593 }
2594 }
2595 }
2596
2597 scope.or_else(|| {
2598 self.language.clone().map(|language| LanguageScope {
2599 language,
2600 override_id: None,
2601 })
2602 })
2603 }
2604
2605 /// Returns a tuple of the range and character kind of the word
2606 /// surrounding the given position.
2607 pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2608 let mut start = start.to_offset(self);
2609 let mut end = start;
2610 let mut next_chars = self.chars_at(start).peekable();
2611 let mut prev_chars = self.reversed_chars_at(start).peekable();
2612
2613 let scope = self.language_scope_at(start);
2614 let kind = |c| char_kind(&scope, c);
2615 let word_kind = cmp::max(
2616 prev_chars.peek().copied().map(kind),
2617 next_chars.peek().copied().map(kind),
2618 );
2619
2620 for ch in prev_chars {
2621 if Some(kind(ch)) == word_kind && ch != '\n' {
2622 start -= ch.len_utf8();
2623 } else {
2624 break;
2625 }
2626 }
2627
2628 for ch in next_chars {
2629 if Some(kind(ch)) == word_kind && ch != '\n' {
2630 end += ch.len_utf8();
2631 } else {
2632 break;
2633 }
2634 }
2635
2636 (start..end, word_kind)
2637 }
2638
2639 /// Returns the range for the closes syntax node enclosing the given range.
2640 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2641 let range = range.start.to_offset(self)..range.end.to_offset(self);
2642 let mut result: Option<Range<usize>> = None;
2643 'outer: for layer in self.syntax.layers_for_range(range.clone(), &self.text) {
2644 let mut cursor = layer.node().walk();
2645
2646 // Descend to the first leaf that touches the start of the range,
2647 // and if the range is non-empty, extends beyond the start.
2648 while cursor.goto_first_child_for_byte(range.start).is_some() {
2649 if !range.is_empty() && cursor.node().end_byte() == range.start {
2650 cursor.goto_next_sibling();
2651 }
2652 }
2653
2654 // Ascend to the smallest ancestor that strictly contains the range.
2655 loop {
2656 let node_range = cursor.node().byte_range();
2657 if node_range.start <= range.start
2658 && node_range.end >= range.end
2659 && node_range.len() > range.len()
2660 {
2661 break;
2662 }
2663 if !cursor.goto_parent() {
2664 continue 'outer;
2665 }
2666 }
2667
2668 let left_node = cursor.node();
2669 let mut layer_result = left_node.byte_range();
2670
2671 // For an empty range, try to find another node immediately to the right of the range.
2672 if left_node.end_byte() == range.start {
2673 let mut right_node = None;
2674 while !cursor.goto_next_sibling() {
2675 if !cursor.goto_parent() {
2676 break;
2677 }
2678 }
2679
2680 while cursor.node().start_byte() == range.start {
2681 right_node = Some(cursor.node());
2682 if !cursor.goto_first_child() {
2683 break;
2684 }
2685 }
2686
2687 // If there is a candidate node on both sides of the (empty) range, then
2688 // decide between the two by favoring a named node over an anonymous token.
2689 // If both nodes are the same in that regard, favor the right one.
2690 if let Some(right_node) = right_node {
2691 if right_node.is_named() || !left_node.is_named() {
2692 layer_result = right_node.byte_range();
2693 }
2694 }
2695 }
2696
2697 if let Some(previous_result) = &result {
2698 if previous_result.len() < layer_result.len() {
2699 continue;
2700 }
2701 }
2702 result = Some(layer_result);
2703 }
2704
2705 result
2706 }
2707
2708 /// Returns the outline for the buffer.
2709 ///
2710 /// This method allows passing an optional [SyntaxTheme] to
2711 /// syntax-highlight the returned symbols.
2712 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2713 self.outline_items_containing(0..self.len(), true, theme)
2714 .map(Outline::new)
2715 }
2716
2717 /// Returns all the symbols that contain the given position.
2718 ///
2719 /// This method allows passing an optional [SyntaxTheme] to
2720 /// syntax-highlight the returned symbols.
2721 pub fn symbols_containing<T: ToOffset>(
2722 &self,
2723 position: T,
2724 theme: Option<&SyntaxTheme>,
2725 ) -> Option<Vec<OutlineItem<Anchor>>> {
2726 let position = position.to_offset(self);
2727 let mut items = self.outline_items_containing(
2728 position.saturating_sub(1)..self.len().min(position + 1),
2729 false,
2730 theme,
2731 )?;
2732 let mut prev_depth = None;
2733 items.retain(|item| {
2734 let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
2735 prev_depth = Some(item.depth);
2736 result
2737 });
2738 Some(items)
2739 }
2740
2741 pub fn outline_items_containing<T: ToOffset>(
2742 &self,
2743 range: Range<T>,
2744 include_extra_context: bool,
2745 theme: Option<&SyntaxTheme>,
2746 ) -> Option<Vec<OutlineItem<Anchor>>> {
2747 let range = range.to_offset(self);
2748 let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2749 grammar.outline_config.as_ref().map(|c| &c.query)
2750 });
2751 let configs = matches
2752 .grammars()
2753 .iter()
2754 .map(|g| g.outline_config.as_ref().unwrap())
2755 .collect::<Vec<_>>();
2756
2757 let mut items = Vec::new();
2758 let mut annotation_row_ranges: Vec<Range<u32>> = Vec::new();
2759 while let Some(mat) = matches.peek() {
2760 let config = &configs[mat.grammar_index];
2761 if let Some(item) =
2762 self.next_outline_item(config, &mat, &range, include_extra_context, theme)
2763 {
2764 items.push(item);
2765 } else if let Some(capture) = mat
2766 .captures
2767 .iter()
2768 .find(|capture| Some(capture.index) == config.annotation_capture_ix)
2769 {
2770 let capture_range = capture.node.start_position()..capture.node.end_position();
2771 let mut capture_row_range =
2772 capture_range.start.row as u32..capture_range.end.row as u32;
2773 if capture_range.end.row > capture_range.start.row && capture_range.end.column == 0
2774 {
2775 capture_row_range.end -= 1;
2776 }
2777 if let Some(last_row_range) = annotation_row_ranges.last_mut() {
2778 if last_row_range.end >= capture_row_range.start.saturating_sub(1) {
2779 last_row_range.end = capture_row_range.end;
2780 } else {
2781 annotation_row_ranges.push(capture_row_range);
2782 }
2783 } else {
2784 annotation_row_ranges.push(capture_row_range);
2785 }
2786 }
2787 matches.advance();
2788 }
2789
2790 items.sort_by_key(|item| (item.range.start, Reverse(item.range.end)));
2791
2792 // Assign depths based on containment relationships and convert to anchors.
2793 let mut item_ends_stack = Vec::<Point>::new();
2794 let mut anchor_items = Vec::new();
2795 let mut annotation_row_ranges = annotation_row_ranges.into_iter().peekable();
2796 for item in items {
2797 while let Some(last_end) = item_ends_stack.last().copied() {
2798 if last_end < item.range.end {
2799 item_ends_stack.pop();
2800 } else {
2801 break;
2802 }
2803 }
2804
2805 let mut annotation_row_range = None;
2806 while let Some(next_annotation_row_range) = annotation_row_ranges.peek() {
2807 let row_preceding_item = item.range.start.row.saturating_sub(1);
2808 if next_annotation_row_range.end < row_preceding_item {
2809 annotation_row_ranges.next();
2810 } else {
2811 if next_annotation_row_range.end == row_preceding_item {
2812 annotation_row_range = Some(next_annotation_row_range.clone());
2813 annotation_row_ranges.next();
2814 }
2815 break;
2816 }
2817 }
2818
2819 anchor_items.push(OutlineItem {
2820 depth: item_ends_stack.len(),
2821 range: self.anchor_after(item.range.start)..self.anchor_before(item.range.end),
2822 text: item.text,
2823 highlight_ranges: item.highlight_ranges,
2824 name_ranges: item.name_ranges,
2825 body_range: item.body_range.map(|body_range| {
2826 self.anchor_after(body_range.start)..self.anchor_before(body_range.end)
2827 }),
2828 annotation_range: annotation_row_range.map(|annotation_range| {
2829 self.anchor_after(Point::new(annotation_range.start, 0))
2830 ..self.anchor_before(Point::new(
2831 annotation_range.end,
2832 self.line_len(annotation_range.end),
2833 ))
2834 }),
2835 });
2836 item_ends_stack.push(item.range.end);
2837 }
2838
2839 Some(anchor_items)
2840 }
2841
2842 fn next_outline_item(
2843 &self,
2844 config: &OutlineConfig,
2845 mat: &SyntaxMapMatch,
2846 range: &Range<usize>,
2847 include_extra_context: bool,
2848 theme: Option<&SyntaxTheme>,
2849 ) -> Option<OutlineItem<Point>> {
2850 let item_node = mat.captures.iter().find_map(|cap| {
2851 if cap.index == config.item_capture_ix {
2852 Some(cap.node)
2853 } else {
2854 None
2855 }
2856 })?;
2857
2858 let item_byte_range = item_node.byte_range();
2859 if item_byte_range.end < range.start || item_byte_range.start > range.end {
2860 return None;
2861 }
2862 let item_point_range = Point::from_ts_point(item_node.start_position())
2863 ..Point::from_ts_point(item_node.end_position());
2864
2865 let mut open_point = None;
2866 let mut close_point = None;
2867 let mut buffer_ranges = Vec::new();
2868 for capture in mat.captures {
2869 let node_is_name;
2870 if capture.index == config.name_capture_ix {
2871 node_is_name = true;
2872 } else if Some(capture.index) == config.context_capture_ix
2873 || (Some(capture.index) == config.extra_context_capture_ix && include_extra_context)
2874 {
2875 node_is_name = false;
2876 } else {
2877 if Some(capture.index) == config.open_capture_ix {
2878 open_point = Some(Point::from_ts_point(capture.node.end_position()));
2879 } else if Some(capture.index) == config.close_capture_ix {
2880 close_point = Some(Point::from_ts_point(capture.node.start_position()));
2881 }
2882
2883 continue;
2884 }
2885
2886 let mut range = capture.node.start_byte()..capture.node.end_byte();
2887 let start = capture.node.start_position();
2888 if capture.node.end_position().row > start.row {
2889 range.end = range.start + self.line_len(start.row as u32) as usize - start.column;
2890 }
2891
2892 if !range.is_empty() {
2893 buffer_ranges.push((range, node_is_name));
2894 }
2895 }
2896 if buffer_ranges.is_empty() {
2897 return None;
2898 }
2899 let mut text = String::new();
2900 let mut highlight_ranges = Vec::new();
2901 let mut name_ranges = Vec::new();
2902 let mut chunks = self.chunks(
2903 buffer_ranges.first().unwrap().0.start..buffer_ranges.last().unwrap().0.end,
2904 true,
2905 );
2906 let mut last_buffer_range_end = 0;
2907 for (buffer_range, is_name) in buffer_ranges {
2908 if !text.is_empty() && buffer_range.start > last_buffer_range_end {
2909 text.push(' ');
2910 }
2911 last_buffer_range_end = buffer_range.end;
2912 if is_name {
2913 let mut start = text.len();
2914 let end = start + buffer_range.len();
2915
2916 // When multiple names are captured, then the matcheable text
2917 // includes the whitespace in between the names.
2918 if !name_ranges.is_empty() {
2919 start -= 1;
2920 }
2921
2922 name_ranges.push(start..end);
2923 }
2924
2925 let mut offset = buffer_range.start;
2926 chunks.seek(buffer_range.clone());
2927 for mut chunk in chunks.by_ref() {
2928 if chunk.text.len() > buffer_range.end - offset {
2929 chunk.text = &chunk.text[0..(buffer_range.end - offset)];
2930 offset = buffer_range.end;
2931 } else {
2932 offset += chunk.text.len();
2933 }
2934 let style = chunk
2935 .syntax_highlight_id
2936 .zip(theme)
2937 .and_then(|(highlight, theme)| highlight.style(theme));
2938 if let Some(style) = style {
2939 let start = text.len();
2940 let end = start + chunk.text.len();
2941 highlight_ranges.push((start..end, style));
2942 }
2943 text.push_str(chunk.text);
2944 if offset >= buffer_range.end {
2945 break;
2946 }
2947 }
2948 }
2949
2950 Some(OutlineItem {
2951 depth: 0, // We'll calculate the depth later
2952 range: item_point_range,
2953 text,
2954 highlight_ranges,
2955 name_ranges,
2956 body_range: open_point.zip(close_point).map(|(start, end)| start..end),
2957 annotation_range: None,
2958 })
2959 }
2960
2961 /// For each grammar in the language, runs the provided
2962 /// [tree_sitter::Query] against the given range.
2963 pub fn matches(
2964 &self,
2965 range: Range<usize>,
2966 query: fn(&Grammar) -> Option<&tree_sitter::Query>,
2967 ) -> SyntaxMapMatches {
2968 self.syntax.matches(range, self, query)
2969 }
2970
2971 /// Returns bracket range pairs overlapping or adjacent to `range`
2972 pub fn bracket_ranges<T: ToOffset>(
2973 &self,
2974 range: Range<T>,
2975 ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
2976 // Find bracket pairs that *inclusively* contain the given range.
2977 let range = range.start.to_offset(self).saturating_sub(1)
2978 ..self.len().min(range.end.to_offset(self) + 1);
2979
2980 let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
2981 grammar.brackets_config.as_ref().map(|c| &c.query)
2982 });
2983 let configs = matches
2984 .grammars()
2985 .iter()
2986 .map(|grammar| grammar.brackets_config.as_ref().unwrap())
2987 .collect::<Vec<_>>();
2988
2989 iter::from_fn(move || {
2990 while let Some(mat) = matches.peek() {
2991 let mut open = None;
2992 let mut close = None;
2993 let config = &configs[mat.grammar_index];
2994 for capture in mat.captures {
2995 if capture.index == config.open_capture_ix {
2996 open = Some(capture.node.byte_range());
2997 } else if capture.index == config.close_capture_ix {
2998 close = Some(capture.node.byte_range());
2999 }
3000 }
3001
3002 matches.advance();
3003
3004 let Some((open, close)) = open.zip(close) else {
3005 continue;
3006 };
3007
3008 let bracket_range = open.start..=close.end;
3009 if !bracket_range.overlaps(&range) {
3010 continue;
3011 }
3012
3013 return Some((open, close));
3014 }
3015 None
3016 })
3017 }
3018
3019 /// Returns enclosing bracket ranges containing the given range
3020 pub fn enclosing_bracket_ranges<T: ToOffset>(
3021 &self,
3022 range: Range<T>,
3023 ) -> impl Iterator<Item = (Range<usize>, Range<usize>)> + '_ {
3024 let range = range.start.to_offset(self)..range.end.to_offset(self);
3025
3026 self.bracket_ranges(range.clone())
3027 .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
3028 }
3029
3030 /// Returns the smallest enclosing bracket ranges containing the given range or None if no brackets contain range
3031 ///
3032 /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3033 pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3034 &self,
3035 range: Range<T>,
3036 range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3037 ) -> Option<(Range<usize>, Range<usize>)> {
3038 let range = range.start.to_offset(self)..range.end.to_offset(self);
3039
3040 // Get the ranges of the innermost pair of brackets.
3041 let mut result: Option<(Range<usize>, Range<usize>)> = None;
3042
3043 for (open, close) in self.enclosing_bracket_ranges(range.clone()) {
3044 if let Some(range_filter) = range_filter {
3045 if !range_filter(open.clone(), close.clone()) {
3046 continue;
3047 }
3048 }
3049
3050 let len = close.end - open.start;
3051
3052 if let Some((existing_open, existing_close)) = &result {
3053 let existing_len = existing_close.end - existing_open.start;
3054 if len > existing_len {
3055 continue;
3056 }
3057 }
3058
3059 result = Some((open, close));
3060 }
3061
3062 result
3063 }
3064
3065 /// Returns anchor ranges for any matches of the redaction query.
3066 /// The buffer can be associated with multiple languages, and the redaction query associated with each
3067 /// will be run on the relevant section of the buffer.
3068 pub fn redacted_ranges<T: ToOffset>(
3069 &self,
3070 range: Range<T>,
3071 ) -> impl Iterator<Item = Range<usize>> + '_ {
3072 let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3073 let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3074 grammar
3075 .redactions_config
3076 .as_ref()
3077 .map(|config| &config.query)
3078 });
3079
3080 let configs = syntax_matches
3081 .grammars()
3082 .iter()
3083 .map(|grammar| grammar.redactions_config.as_ref())
3084 .collect::<Vec<_>>();
3085
3086 iter::from_fn(move || {
3087 let redacted_range = syntax_matches
3088 .peek()
3089 .and_then(|mat| {
3090 configs[mat.grammar_index].and_then(|config| {
3091 mat.captures
3092 .iter()
3093 .find(|capture| capture.index == config.redaction_capture_ix)
3094 })
3095 })
3096 .map(|mat| mat.node.byte_range());
3097 syntax_matches.advance();
3098 redacted_range
3099 })
3100 }
3101
3102 pub fn injections_intersecting_range<T: ToOffset>(
3103 &self,
3104 range: Range<T>,
3105 ) -> impl Iterator<Item = (Range<usize>, &Arc<Language>)> + '_ {
3106 let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3107
3108 let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3109 grammar
3110 .injection_config
3111 .as_ref()
3112 .map(|config| &config.query)
3113 });
3114
3115 let configs = syntax_matches
3116 .grammars()
3117 .iter()
3118 .map(|grammar| grammar.injection_config.as_ref())
3119 .collect::<Vec<_>>();
3120
3121 iter::from_fn(move || {
3122 let ranges = syntax_matches.peek().and_then(|mat| {
3123 let config = &configs[mat.grammar_index]?;
3124 let content_capture_range = mat.captures.iter().find_map(|capture| {
3125 if capture.index == config.content_capture_ix {
3126 Some(capture.node.byte_range())
3127 } else {
3128 None
3129 }
3130 })?;
3131 let language = self.language_at(content_capture_range.start)?;
3132 Some((content_capture_range, language))
3133 });
3134 syntax_matches.advance();
3135 ranges
3136 })
3137 }
3138
3139 pub fn runnable_ranges(
3140 &self,
3141 range: Range<Anchor>,
3142 ) -> impl Iterator<Item = RunnableRange> + '_ {
3143 let offset_range = range.start.to_offset(self)..range.end.to_offset(self);
3144
3145 let mut syntax_matches = self.syntax.matches(offset_range, self, |grammar| {
3146 grammar.runnable_config.as_ref().map(|config| &config.query)
3147 });
3148
3149 let test_configs = syntax_matches
3150 .grammars()
3151 .iter()
3152 .map(|grammar| grammar.runnable_config.as_ref())
3153 .collect::<Vec<_>>();
3154
3155 iter::from_fn(move || loop {
3156 let mat = syntax_matches.peek()?;
3157
3158 let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
3159 let mut run_range = None;
3160 let full_range = mat.captures.iter().fold(
3161 Range {
3162 start: usize::MAX,
3163 end: 0,
3164 },
3165 |mut acc, next| {
3166 let byte_range = next.node.byte_range();
3167 if acc.start > byte_range.start {
3168 acc.start = byte_range.start;
3169 }
3170 if acc.end < byte_range.end {
3171 acc.end = byte_range.end;
3172 }
3173 acc
3174 },
3175 );
3176 if full_range.start > full_range.end {
3177 // We did not find a full spanning range of this match.
3178 return None;
3179 }
3180 let extra_captures: SmallVec<[_; 1]> =
3181 SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
3182 test_configs
3183 .extra_captures
3184 .get(capture.index as usize)
3185 .cloned()
3186 .and_then(|tag_name| match tag_name {
3187 RunnableCapture::Named(name) => {
3188 Some((capture.node.byte_range(), name))
3189 }
3190 RunnableCapture::Run => {
3191 let _ = run_range.insert(capture.node.byte_range());
3192 None
3193 }
3194 })
3195 }));
3196 let run_range = run_range?;
3197 let tags = test_configs
3198 .query
3199 .property_settings(mat.pattern_index)
3200 .iter()
3201 .filter_map(|property| {
3202 if *property.key == *"tag" {
3203 property
3204 .value
3205 .as_ref()
3206 .map(|value| RunnableTag(value.to_string().into()))
3207 } else {
3208 None
3209 }
3210 })
3211 .collect();
3212 let extra_captures = extra_captures
3213 .into_iter()
3214 .map(|(range, name)| {
3215 (
3216 name.to_string(),
3217 self.text_for_range(range.clone()).collect::<String>(),
3218 )
3219 })
3220 .collect();
3221 // All tags should have the same range.
3222 Some(RunnableRange {
3223 run_range,
3224 full_range,
3225 runnable: Runnable {
3226 tags,
3227 language: mat.language,
3228 buffer: self.remote_id(),
3229 },
3230 extra_captures,
3231 buffer_id: self.remote_id(),
3232 })
3233 });
3234
3235 syntax_matches.advance();
3236 if test_range.is_some() {
3237 // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
3238 // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
3239 return test_range;
3240 }
3241 })
3242 }
3243
3244 pub fn indent_guides_in_range(
3245 &self,
3246 range: Range<Anchor>,
3247 ignore_disabled_for_language: bool,
3248 cx: &AppContext,
3249 ) -> Vec<IndentGuide> {
3250 let language_settings = language_settings(self.language(), self.file.as_ref(), cx);
3251 let settings = language_settings.indent_guides;
3252 if !ignore_disabled_for_language && !settings.enabled {
3253 return Vec::new();
3254 }
3255 let tab_size = language_settings.tab_size.get() as u32;
3256
3257 let start_row = range.start.to_point(self).row;
3258 let end_row = range.end.to_point(self).row;
3259 let row_range = start_row..end_row + 1;
3260
3261 let mut row_indents = self.line_indents_in_row_range(row_range.clone());
3262
3263 let mut result_vec = Vec::new();
3264 let mut indent_stack = SmallVec::<[IndentGuide; 8]>::new();
3265
3266 while let Some((first_row, mut line_indent)) = row_indents.next() {
3267 let current_depth = indent_stack.len() as u32;
3268
3269 // When encountering empty, continue until found useful line indent
3270 // then add to the indent stack with the depth found
3271 let mut found_indent = false;
3272 let mut last_row = first_row;
3273 if line_indent.is_line_empty() {
3274 let mut trailing_row = end_row;
3275 while !found_indent {
3276 let (target_row, new_line_indent) =
3277 if let Some(display_row) = row_indents.next() {
3278 display_row
3279 } else {
3280 // This means we reached the end of the given range and found empty lines at the end.
3281 // We need to traverse further until we find a non-empty line to know if we need to add
3282 // an indent guide for the last visible indent.
3283 trailing_row += 1;
3284
3285 const TRAILING_ROW_SEARCH_LIMIT: u32 = 25;
3286 if trailing_row > self.max_point().row
3287 || trailing_row > end_row + TRAILING_ROW_SEARCH_LIMIT
3288 {
3289 break;
3290 }
3291 let new_line_indent = self.line_indent_for_row(trailing_row);
3292 (trailing_row, new_line_indent)
3293 };
3294
3295 if new_line_indent.is_line_empty() {
3296 continue;
3297 }
3298 last_row = target_row.min(end_row);
3299 line_indent = new_line_indent;
3300 found_indent = true;
3301 break;
3302 }
3303 } else {
3304 found_indent = true
3305 }
3306
3307 let depth = if found_indent {
3308 line_indent.len(tab_size) / tab_size
3309 + ((line_indent.len(tab_size) % tab_size) > 0) as u32
3310 } else {
3311 current_depth
3312 };
3313
3314 if depth < current_depth {
3315 for _ in 0..(current_depth - depth) {
3316 let mut indent = indent_stack.pop().unwrap();
3317 if last_row != first_row {
3318 // In this case, we landed on an empty row, had to seek forward,
3319 // and discovered that the indent we where on is ending.
3320 // This means that the last display row must
3321 // be on line that ends this indent range, so we
3322 // should display the range up to the first non-empty line
3323 indent.end_row = first_row.saturating_sub(1);
3324 }
3325
3326 result_vec.push(indent)
3327 }
3328 } else if depth > current_depth {
3329 for next_depth in current_depth..depth {
3330 indent_stack.push(IndentGuide {
3331 buffer_id: self.remote_id(),
3332 start_row: first_row,
3333 end_row: last_row,
3334 depth: next_depth,
3335 tab_size,
3336 settings,
3337 });
3338 }
3339 }
3340
3341 for indent in indent_stack.iter_mut() {
3342 indent.end_row = last_row;
3343 }
3344 }
3345
3346 result_vec.extend(indent_stack);
3347
3348 result_vec
3349 }
3350
3351 pub async fn enclosing_indent(
3352 &self,
3353 mut buffer_row: BufferRow,
3354 ) -> Option<(Range<BufferRow>, LineIndent)> {
3355 let max_row = self.max_point().row;
3356 if buffer_row >= max_row {
3357 return None;
3358 }
3359
3360 let mut target_indent = self.line_indent_for_row(buffer_row);
3361
3362 // If the current row is at the start of an indented block, we want to return this
3363 // block as the enclosing indent.
3364 if !target_indent.is_line_empty() && buffer_row < max_row {
3365 let next_line_indent = self.line_indent_for_row(buffer_row + 1);
3366 if !next_line_indent.is_line_empty()
3367 && target_indent.raw_len() < next_line_indent.raw_len()
3368 {
3369 target_indent = next_line_indent;
3370 buffer_row += 1;
3371 }
3372 }
3373
3374 const SEARCH_ROW_LIMIT: u32 = 25000;
3375 const SEARCH_WHITESPACE_ROW_LIMIT: u32 = 2500;
3376 const YIELD_INTERVAL: u32 = 100;
3377
3378 let mut accessed_row_counter = 0;
3379
3380 // If there is a blank line at the current row, search for the next non indented lines
3381 if target_indent.is_line_empty() {
3382 let start = buffer_row.saturating_sub(SEARCH_WHITESPACE_ROW_LIMIT);
3383 let end = (max_row + 1).min(buffer_row + SEARCH_WHITESPACE_ROW_LIMIT);
3384
3385 let mut non_empty_line_above = None;
3386 for (row, indent) in self
3387 .text
3388 .reversed_line_indents_in_row_range(start..buffer_row)
3389 {
3390 accessed_row_counter += 1;
3391 if accessed_row_counter == YIELD_INTERVAL {
3392 accessed_row_counter = 0;
3393 yield_now().await;
3394 }
3395 if !indent.is_line_empty() {
3396 non_empty_line_above = Some((row, indent));
3397 break;
3398 }
3399 }
3400
3401 let mut non_empty_line_below = None;
3402 for (row, indent) in self.text.line_indents_in_row_range((buffer_row + 1)..end) {
3403 accessed_row_counter += 1;
3404 if accessed_row_counter == YIELD_INTERVAL {
3405 accessed_row_counter = 0;
3406 yield_now().await;
3407 }
3408 if !indent.is_line_empty() {
3409 non_empty_line_below = Some((row, indent));
3410 break;
3411 }
3412 }
3413
3414 let (row, indent) = match (non_empty_line_above, non_empty_line_below) {
3415 (Some((above_row, above_indent)), Some((below_row, below_indent))) => {
3416 if above_indent.raw_len() >= below_indent.raw_len() {
3417 (above_row, above_indent)
3418 } else {
3419 (below_row, below_indent)
3420 }
3421 }
3422 (Some(above), None) => above,
3423 (None, Some(below)) => below,
3424 _ => return None,
3425 };
3426
3427 target_indent = indent;
3428 buffer_row = row;
3429 }
3430
3431 let start = buffer_row.saturating_sub(SEARCH_ROW_LIMIT);
3432 let end = (max_row + 1).min(buffer_row + SEARCH_ROW_LIMIT);
3433
3434 let mut start_indent = None;
3435 for (row, indent) in self
3436 .text
3437 .reversed_line_indents_in_row_range(start..buffer_row)
3438 {
3439 accessed_row_counter += 1;
3440 if accessed_row_counter == YIELD_INTERVAL {
3441 accessed_row_counter = 0;
3442 yield_now().await;
3443 }
3444 if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
3445 start_indent = Some((row, indent));
3446 break;
3447 }
3448 }
3449 let (start_row, start_indent_size) = start_indent?;
3450
3451 let mut end_indent = (end, None);
3452 for (row, indent) in self.text.line_indents_in_row_range((buffer_row + 1)..end) {
3453 accessed_row_counter += 1;
3454 if accessed_row_counter == YIELD_INTERVAL {
3455 accessed_row_counter = 0;
3456 yield_now().await;
3457 }
3458 if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
3459 end_indent = (row.saturating_sub(1), Some(indent));
3460 break;
3461 }
3462 }
3463 let (end_row, end_indent_size) = end_indent;
3464
3465 let indent = if let Some(end_indent_size) = end_indent_size {
3466 if start_indent_size.raw_len() > end_indent_size.raw_len() {
3467 start_indent_size
3468 } else {
3469 end_indent_size
3470 }
3471 } else {
3472 start_indent_size
3473 };
3474
3475 Some((start_row..end_row, indent))
3476 }
3477
3478 /// Returns selections for remote peers intersecting the given range.
3479 #[allow(clippy::type_complexity)]
3480 pub fn selections_in_range(
3481 &self,
3482 range: Range<Anchor>,
3483 include_local: bool,
3484 ) -> impl Iterator<
3485 Item = (
3486 ReplicaId,
3487 bool,
3488 CursorShape,
3489 impl Iterator<Item = &Selection<Anchor>> + '_,
3490 ),
3491 > + '_ {
3492 self.remote_selections
3493 .iter()
3494 .filter(move |(replica_id, set)| {
3495 (include_local || **replica_id != self.text.replica_id())
3496 && !set.selections.is_empty()
3497 })
3498 .map(move |(replica_id, set)| {
3499 let start_ix = match set.selections.binary_search_by(|probe| {
3500 probe.end.cmp(&range.start, self).then(Ordering::Greater)
3501 }) {
3502 Ok(ix) | Err(ix) => ix,
3503 };
3504 let end_ix = match set.selections.binary_search_by(|probe| {
3505 probe.start.cmp(&range.end, self).then(Ordering::Less)
3506 }) {
3507 Ok(ix) | Err(ix) => ix,
3508 };
3509
3510 (
3511 *replica_id,
3512 set.line_mode,
3513 set.cursor_shape,
3514 set.selections[start_ix..end_ix].iter(),
3515 )
3516 })
3517 }
3518
3519 /// Whether the buffer contains any git changes.
3520 pub fn has_git_diff(&self) -> bool {
3521 !self.git_diff.is_empty()
3522 }
3523
3524 /// Returns all the Git diff hunks intersecting the given
3525 /// row range.
3526 pub fn git_diff_hunks_in_row_range(
3527 &self,
3528 range: Range<BufferRow>,
3529 ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3530 self.git_diff.hunks_in_row_range(range, self)
3531 }
3532
3533 /// Returns all the Git diff hunks intersecting the given
3534 /// range.
3535 pub fn git_diff_hunks_intersecting_range(
3536 &self,
3537 range: Range<Anchor>,
3538 ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3539 self.git_diff.hunks_intersecting_range(range, self)
3540 }
3541
3542 /// Returns all the Git diff hunks intersecting the given
3543 /// range, in reverse order.
3544 pub fn git_diff_hunks_intersecting_range_rev(
3545 &self,
3546 range: Range<Anchor>,
3547 ) -> impl '_ + Iterator<Item = git::diff::DiffHunk<u32>> {
3548 self.git_diff.hunks_intersecting_range_rev(range, self)
3549 }
3550
3551 /// Returns if the buffer contains any diagnostics.
3552 pub fn has_diagnostics(&self) -> bool {
3553 !self.diagnostics.is_empty()
3554 }
3555
3556 /// Returns all the diagnostics intersecting the given range.
3557 pub fn diagnostics_in_range<'a, T, O>(
3558 &'a self,
3559 search_range: Range<T>,
3560 reversed: bool,
3561 ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3562 where
3563 T: 'a + Clone + ToOffset,
3564 O: 'a + FromAnchor + Ord,
3565 {
3566 let mut iterators: Vec<_> = self
3567 .diagnostics
3568 .iter()
3569 .map(|(_, collection)| {
3570 collection
3571 .range::<T, O>(search_range.clone(), self, true, reversed)
3572 .peekable()
3573 })
3574 .collect();
3575
3576 std::iter::from_fn(move || {
3577 let (next_ix, _) = iterators
3578 .iter_mut()
3579 .enumerate()
3580 .flat_map(|(ix, iter)| Some((ix, iter.peek()?)))
3581 .min_by(|(_, a), (_, b)| {
3582 let cmp = a
3583 .range
3584 .start
3585 .cmp(&b.range.start)
3586 // when range is equal, sort by diagnostic severity
3587 .then(a.diagnostic.severity.cmp(&b.diagnostic.severity))
3588 // and stabilize order with group_id
3589 .then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
3590 if reversed {
3591 cmp.reverse()
3592 } else {
3593 cmp
3594 }
3595 })?;
3596 iterators[next_ix].next()
3597 })
3598 }
3599
3600 /// Returns all the diagnostic groups associated with the given
3601 /// language server id. If no language server id is provided,
3602 /// all diagnostics groups are returned.
3603 pub fn diagnostic_groups(
3604 &self,
3605 language_server_id: Option<LanguageServerId>,
3606 ) -> Vec<(LanguageServerId, DiagnosticGroup<Anchor>)> {
3607 let mut groups = Vec::new();
3608
3609 if let Some(language_server_id) = language_server_id {
3610 if let Ok(ix) = self
3611 .diagnostics
3612 .binary_search_by_key(&language_server_id, |e| e.0)
3613 {
3614 self.diagnostics[ix]
3615 .1
3616 .groups(language_server_id, &mut groups, self);
3617 }
3618 } else {
3619 for (language_server_id, diagnostics) in self.diagnostics.iter() {
3620 diagnostics.groups(*language_server_id, &mut groups, self);
3621 }
3622 }
3623
3624 groups.sort_by(|(id_a, group_a), (id_b, group_b)| {
3625 let a_start = &group_a.entries[group_a.primary_ix].range.start;
3626 let b_start = &group_b.entries[group_b.primary_ix].range.start;
3627 a_start.cmp(b_start, self).then_with(|| id_a.cmp(id_b))
3628 });
3629
3630 groups
3631 }
3632
3633 /// Returns an iterator over the diagnostics for the given group.
3634 pub fn diagnostic_group<'a, O>(
3635 &'a self,
3636 group_id: usize,
3637 ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
3638 where
3639 O: 'a + FromAnchor,
3640 {
3641 self.diagnostics
3642 .iter()
3643 .flat_map(move |(_, set)| set.group(group_id, self))
3644 }
3645
3646 /// An integer version number that accounts for all updates besides
3647 /// the buffer's text itself (which is versioned via a version vector).
3648 pub fn non_text_state_update_count(&self) -> usize {
3649 self.non_text_state_update_count
3650 }
3651
3652 /// Returns a snapshot of underlying file.
3653 pub fn file(&self) -> Option<&Arc<dyn File>> {
3654 self.file.as_ref()
3655 }
3656
3657 /// Resolves the file path (relative to the worktree root) associated with the underlying file.
3658 pub fn resolve_file_path(&self, cx: &AppContext, include_root: bool) -> Option<PathBuf> {
3659 if let Some(file) = self.file() {
3660 if file.path().file_name().is_none() || include_root {
3661 Some(file.full_path(cx))
3662 } else {
3663 Some(file.path().to_path_buf())
3664 }
3665 } else {
3666 None
3667 }
3668 }
3669}
3670
3671fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
3672 indent_size_for_text(text.chars_at(Point::new(row, 0)))
3673}
3674
3675fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
3676 let mut result = IndentSize::spaces(0);
3677 for c in text {
3678 let kind = match c {
3679 ' ' => IndentKind::Space,
3680 '\t' => IndentKind::Tab,
3681 _ => break,
3682 };
3683 if result.len == 0 {
3684 result.kind = kind;
3685 }
3686 result.len += 1;
3687 }
3688 result
3689}
3690
3691impl Clone for BufferSnapshot {
3692 fn clone(&self) -> Self {
3693 Self {
3694 text: self.text.clone(),
3695 git_diff: self.git_diff.clone(),
3696 syntax: self.syntax.clone(),
3697 file: self.file.clone(),
3698 remote_selections: self.remote_selections.clone(),
3699 diagnostics: self.diagnostics.clone(),
3700 language: self.language.clone(),
3701 non_text_state_update_count: self.non_text_state_update_count,
3702 }
3703 }
3704}
3705
3706impl Deref for BufferSnapshot {
3707 type Target = text::BufferSnapshot;
3708
3709 fn deref(&self) -> &Self::Target {
3710 &self.text
3711 }
3712}
3713
3714unsafe impl<'a> Send for BufferChunks<'a> {}
3715
3716impl<'a> BufferChunks<'a> {
3717 pub(crate) fn new(
3718 text: &'a Rope,
3719 range: Range<usize>,
3720 syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
3721 buffer_snapshot: Option<&'a BufferSnapshot>,
3722 ) -> Self {
3723 let mut highlights = None;
3724 if let Some((captures, highlight_maps)) = syntax {
3725 highlights = Some(BufferChunkHighlights {
3726 captures,
3727 next_capture: None,
3728 stack: Default::default(),
3729 highlight_maps,
3730 })
3731 }
3732
3733 let diagnostic_endpoints = Vec::new().into_iter().peekable();
3734 let chunks = text.chunks_in_range(range.clone());
3735
3736 let mut this = BufferChunks {
3737 range,
3738 buffer_snapshot,
3739 chunks,
3740 diagnostic_endpoints,
3741 error_depth: 0,
3742 warning_depth: 0,
3743 information_depth: 0,
3744 hint_depth: 0,
3745 unnecessary_depth: 0,
3746 highlights,
3747 };
3748 this.initialize_diagnostic_endpoints();
3749 this
3750 }
3751
3752 /// Seeks to the given byte offset in the buffer.
3753 pub fn seek(&mut self, range: Range<usize>) {
3754 let old_range = std::mem::replace(&mut self.range, range.clone());
3755 self.chunks.set_range(self.range.clone());
3756 if let Some(highlights) = self.highlights.as_mut() {
3757 if old_range.start >= self.range.start && old_range.end <= self.range.end {
3758 // Reuse existing highlights stack, as the new range is a subrange of the old one.
3759 highlights
3760 .stack
3761 .retain(|(end_offset, _)| *end_offset > range.start);
3762 if let Some(capture) = &highlights.next_capture {
3763 if range.start >= capture.node.start_byte() {
3764 let next_capture_end = capture.node.end_byte();
3765 if range.start < next_capture_end {
3766 highlights.stack.push((
3767 next_capture_end,
3768 highlights.highlight_maps[capture.grammar_index].get(capture.index),
3769 ));
3770 }
3771 highlights.next_capture.take();
3772 }
3773 }
3774 } else if let Some(snapshot) = self.buffer_snapshot {
3775 let (captures, highlight_maps) = snapshot.get_highlights(self.range.clone());
3776 *highlights = BufferChunkHighlights {
3777 captures,
3778 next_capture: None,
3779 stack: Default::default(),
3780 highlight_maps,
3781 };
3782 } else {
3783 // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
3784 // Seeking such BufferChunks is not supported.
3785 debug_assert!(false, "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot");
3786 }
3787
3788 highlights.captures.set_byte_range(self.range.clone());
3789 self.initialize_diagnostic_endpoints();
3790 }
3791 }
3792
3793 fn initialize_diagnostic_endpoints(&mut self) {
3794 if let Some(buffer) = self.buffer_snapshot {
3795 let mut diagnostic_endpoints = Vec::new();
3796 for entry in buffer.diagnostics_in_range::<_, usize>(self.range.clone(), false) {
3797 diagnostic_endpoints.push(DiagnosticEndpoint {
3798 offset: entry.range.start,
3799 is_start: true,
3800 severity: entry.diagnostic.severity,
3801 is_unnecessary: entry.diagnostic.is_unnecessary,
3802 });
3803 diagnostic_endpoints.push(DiagnosticEndpoint {
3804 offset: entry.range.end,
3805 is_start: false,
3806 severity: entry.diagnostic.severity,
3807 is_unnecessary: entry.diagnostic.is_unnecessary,
3808 });
3809 }
3810 diagnostic_endpoints
3811 .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
3812 self.diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
3813 }
3814 }
3815
3816 /// The current byte offset in the buffer.
3817 pub fn offset(&self) -> usize {
3818 self.range.start
3819 }
3820
3821 fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
3822 let depth = match endpoint.severity {
3823 DiagnosticSeverity::ERROR => &mut self.error_depth,
3824 DiagnosticSeverity::WARNING => &mut self.warning_depth,
3825 DiagnosticSeverity::INFORMATION => &mut self.information_depth,
3826 DiagnosticSeverity::HINT => &mut self.hint_depth,
3827 _ => return,
3828 };
3829 if endpoint.is_start {
3830 *depth += 1;
3831 } else {
3832 *depth -= 1;
3833 }
3834
3835 if endpoint.is_unnecessary {
3836 if endpoint.is_start {
3837 self.unnecessary_depth += 1;
3838 } else {
3839 self.unnecessary_depth -= 1;
3840 }
3841 }
3842 }
3843
3844 fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
3845 if self.error_depth > 0 {
3846 Some(DiagnosticSeverity::ERROR)
3847 } else if self.warning_depth > 0 {
3848 Some(DiagnosticSeverity::WARNING)
3849 } else if self.information_depth > 0 {
3850 Some(DiagnosticSeverity::INFORMATION)
3851 } else if self.hint_depth > 0 {
3852 Some(DiagnosticSeverity::HINT)
3853 } else {
3854 None
3855 }
3856 }
3857
3858 fn current_code_is_unnecessary(&self) -> bool {
3859 self.unnecessary_depth > 0
3860 }
3861}
3862
3863impl<'a> Iterator for BufferChunks<'a> {
3864 type Item = Chunk<'a>;
3865
3866 fn next(&mut self) -> Option<Self::Item> {
3867 let mut next_capture_start = usize::MAX;
3868 let mut next_diagnostic_endpoint = usize::MAX;
3869
3870 if let Some(highlights) = self.highlights.as_mut() {
3871 while let Some((parent_capture_end, _)) = highlights.stack.last() {
3872 if *parent_capture_end <= self.range.start {
3873 highlights.stack.pop();
3874 } else {
3875 break;
3876 }
3877 }
3878
3879 if highlights.next_capture.is_none() {
3880 highlights.next_capture = highlights.captures.next();
3881 }
3882
3883 while let Some(capture) = highlights.next_capture.as_ref() {
3884 if self.range.start < capture.node.start_byte() {
3885 next_capture_start = capture.node.start_byte();
3886 break;
3887 } else {
3888 let highlight_id =
3889 highlights.highlight_maps[capture.grammar_index].get(capture.index);
3890 highlights
3891 .stack
3892 .push((capture.node.end_byte(), highlight_id));
3893 highlights.next_capture = highlights.captures.next();
3894 }
3895 }
3896 }
3897
3898 while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
3899 if endpoint.offset <= self.range.start {
3900 self.update_diagnostic_depths(endpoint);
3901 self.diagnostic_endpoints.next();
3902 } else {
3903 next_diagnostic_endpoint = endpoint.offset;
3904 break;
3905 }
3906 }
3907
3908 if let Some(chunk) = self.chunks.peek() {
3909 let chunk_start = self.range.start;
3910 let mut chunk_end = (self.chunks.offset() + chunk.len())
3911 .min(next_capture_start)
3912 .min(next_diagnostic_endpoint);
3913 let mut highlight_id = None;
3914 if let Some(highlights) = self.highlights.as_ref() {
3915 if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
3916 chunk_end = chunk_end.min(*parent_capture_end);
3917 highlight_id = Some(*parent_highlight_id);
3918 }
3919 }
3920
3921 let slice =
3922 &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
3923 self.range.start = chunk_end;
3924 if self.range.start == self.chunks.offset() + chunk.len() {
3925 self.chunks.next().unwrap();
3926 }
3927
3928 Some(Chunk {
3929 text: slice,
3930 syntax_highlight_id: highlight_id,
3931 diagnostic_severity: self.current_diagnostic_severity(),
3932 is_unnecessary: self.current_code_is_unnecessary(),
3933 ..Default::default()
3934 })
3935 } else {
3936 None
3937 }
3938 }
3939}
3940
3941impl operation_queue::Operation for Operation {
3942 fn lamport_timestamp(&self) -> clock::Lamport {
3943 match self {
3944 Operation::Buffer(_) => {
3945 unreachable!("buffer operations should never be deferred at this layer")
3946 }
3947 Operation::UpdateDiagnostics {
3948 lamport_timestamp, ..
3949 }
3950 | Operation::UpdateSelections {
3951 lamport_timestamp, ..
3952 }
3953 | Operation::UpdateCompletionTriggers {
3954 lamport_timestamp, ..
3955 } => *lamport_timestamp,
3956 }
3957 }
3958}
3959
3960impl Default for Diagnostic {
3961 fn default() -> Self {
3962 Self {
3963 source: Default::default(),
3964 code: None,
3965 severity: DiagnosticSeverity::ERROR,
3966 message: Default::default(),
3967 group_id: 0,
3968 is_primary: false,
3969 is_disk_based: false,
3970 is_unnecessary: false,
3971 data: None,
3972 }
3973 }
3974}
3975
3976impl IndentSize {
3977 /// Returns an [IndentSize] representing the given spaces.
3978 pub fn spaces(len: u32) -> Self {
3979 Self {
3980 len,
3981 kind: IndentKind::Space,
3982 }
3983 }
3984
3985 /// Returns an [IndentSize] representing a tab.
3986 pub fn tab() -> Self {
3987 Self {
3988 len: 1,
3989 kind: IndentKind::Tab,
3990 }
3991 }
3992
3993 /// An iterator over the characters represented by this [IndentSize].
3994 pub fn chars(&self) -> impl Iterator<Item = char> {
3995 iter::repeat(self.char()).take(self.len as usize)
3996 }
3997
3998 /// The character representation of this [IndentSize].
3999 pub fn char(&self) -> char {
4000 match self.kind {
4001 IndentKind::Space => ' ',
4002 IndentKind::Tab => '\t',
4003 }
4004 }
4005
4006 /// Consumes the current [IndentSize] and returns a new one that has
4007 /// been shrunk or enlarged by the given size along the given direction.
4008 pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
4009 match direction {
4010 Ordering::Less => {
4011 if self.kind == size.kind && self.len >= size.len {
4012 self.len -= size.len;
4013 }
4014 }
4015 Ordering::Equal => {}
4016 Ordering::Greater => {
4017 if self.len == 0 {
4018 self = size;
4019 } else if self.kind == size.kind {
4020 self.len += size.len;
4021 }
4022 }
4023 }
4024 self
4025 }
4026}
4027
4028#[cfg(any(test, feature = "test-support"))]
4029pub struct TestFile {
4030 pub path: Arc<Path>,
4031 pub root_name: String,
4032}
4033
4034#[cfg(any(test, feature = "test-support"))]
4035impl File for TestFile {
4036 fn path(&self) -> &Arc<Path> {
4037 &self.path
4038 }
4039
4040 fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
4041 PathBuf::from(&self.root_name).join(self.path.as_ref())
4042 }
4043
4044 fn as_local(&self) -> Option<&dyn LocalFile> {
4045 None
4046 }
4047
4048 fn mtime(&self) -> Option<SystemTime> {
4049 unimplemented!()
4050 }
4051
4052 fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
4053 self.path().file_name().unwrap_or(self.root_name.as_ref())
4054 }
4055
4056 fn worktree_id(&self) -> usize {
4057 0
4058 }
4059
4060 fn is_deleted(&self) -> bool {
4061 unimplemented!()
4062 }
4063
4064 fn as_any(&self) -> &dyn std::any::Any {
4065 unimplemented!()
4066 }
4067
4068 fn to_proto(&self, _: &AppContext) -> rpc::proto::File {
4069 unimplemented!()
4070 }
4071
4072 fn is_private(&self) -> bool {
4073 false
4074 }
4075}
4076
4077pub(crate) fn contiguous_ranges(
4078 values: impl Iterator<Item = u32>,
4079 max_len: usize,
4080) -> impl Iterator<Item = Range<u32>> {
4081 let mut values = values;
4082 let mut current_range: Option<Range<u32>> = None;
4083 std::iter::from_fn(move || loop {
4084 if let Some(value) = values.next() {
4085 if let Some(range) = &mut current_range {
4086 if value == range.end && range.len() < max_len {
4087 range.end += 1;
4088 continue;
4089 }
4090 }
4091
4092 let prev_range = current_range.clone();
4093 current_range = Some(value..(value + 1));
4094 if prev_range.is_some() {
4095 return prev_range;
4096 }
4097 } else {
4098 return current_range.take();
4099 }
4100 })
4101}
4102
4103/// Returns the [CharKind] for the given character. When a scope is provided,
4104/// the function checks if the character is considered a word character
4105/// based on the language scope's word character settings.
4106pub fn char_kind(scope: &Option<LanguageScope>, c: char) -> CharKind {
4107 if c.is_whitespace() {
4108 return CharKind::Whitespace;
4109 } else if c.is_alphanumeric() || c == '_' {
4110 return CharKind::Word;
4111 }
4112
4113 if let Some(scope) = scope {
4114 if let Some(characters) = scope.word_characters() {
4115 if characters.contains(&c) {
4116 return CharKind::Word;
4117 }
4118 }
4119 }
4120
4121 CharKind::Punctuation
4122}
4123
4124/// Find all of the ranges of whitespace that occur at the ends of lines
4125/// in the given rope.
4126///
4127/// This could also be done with a regex search, but this implementation
4128/// avoids copying text.
4129pub fn trailing_whitespace_ranges(rope: &Rope) -> Vec<Range<usize>> {
4130 let mut ranges = Vec::new();
4131
4132 let mut offset = 0;
4133 let mut prev_chunk_trailing_whitespace_range = 0..0;
4134 for chunk in rope.chunks() {
4135 let mut prev_line_trailing_whitespace_range = 0..0;
4136 for (i, line) in chunk.split('\n').enumerate() {
4137 let line_end_offset = offset + line.len();
4138 let trimmed_line_len = line.trim_end_matches(|c| matches!(c, ' ' | '\t')).len();
4139 let mut trailing_whitespace_range = (offset + trimmed_line_len)..line_end_offset;
4140
4141 if i == 0 && trimmed_line_len == 0 {
4142 trailing_whitespace_range.start = prev_chunk_trailing_whitespace_range.start;
4143 }
4144 if !prev_line_trailing_whitespace_range.is_empty() {
4145 ranges.push(prev_line_trailing_whitespace_range);
4146 }
4147
4148 offset = line_end_offset + 1;
4149 prev_line_trailing_whitespace_range = trailing_whitespace_range;
4150 }
4151
4152 offset -= 1;
4153 prev_chunk_trailing_whitespace_range = prev_line_trailing_whitespace_range;
4154 }
4155
4156 if !prev_chunk_trailing_whitespace_range.is_empty() {
4157 ranges.push(prev_chunk_trailing_whitespace_range);
4158 }
4159
4160 ranges
4161}