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