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