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