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