1//! The `language` crate provides a large chunk of Zed's language-related
2//! features (the other big contributors being project and lsp crates that revolve around LSP features).
3//! Namely, this crate:
4//! - Provides [`Language`], [`Grammar`] and [`LanguageRegistry`] types that
5//! use Tree-sitter to provide syntax highlighting to the editor; note though that `language` doesn't perform the highlighting by itself. It only maps ranges in a buffer to colors. Treesitter is also used for buffer outlines (lists of symbols in a buffer)
6//! - Exposes [`LanguageConfig`] that describes how constructs (like brackets or line comments) should be handled by the editor for a source file of a particular language.
7//!
8//! Notably we do *not* assign a single language to a single file; in real world a single file can consist of multiple programming languages - HTML is a good example of that - and `language` crate tends to reflect that status quo in its API.
9mod buffer;
10mod diagnostic_set;
11mod highlight_map;
12mod language_registry;
13pub mod language_settings;
14mod manifest;
15mod outline;
16pub mod proto;
17mod syntax_map;
18mod task_context;
19mod text_diff;
20mod toolchain;
21
22#[cfg(test)]
23pub mod buffer_tests;
24
25pub use crate::language_settings::EditPredictionsMode;
26use crate::language_settings::SoftWrap;
27use anyhow::{Context as _, Result};
28use async_trait::async_trait;
29use collections::{HashMap, HashSet, IndexSet};
30use fs::Fs;
31use futures::Future;
32use gpui::{App, AsyncApp, Entity, SharedString, Task};
33pub use highlight_map::HighlightMap;
34use http_client::HttpClient;
35pub use language_registry::{
36 LanguageName, LanguageServerStatusUpdate, LoadedLanguage, ServerHealth,
37};
38use lsp::{CodeActionKind, InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions};
39pub use manifest::{ManifestDelegate, ManifestName, ManifestProvider, ManifestQuery};
40use parking_lot::Mutex;
41use regex::Regex;
42use schemars::{JsonSchema, SchemaGenerator, json_schema};
43use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
44use serde_json::Value;
45use settings::WorktreeId;
46use smol::future::FutureExt as _;
47use std::num::NonZeroU32;
48use std::{
49 any::Any,
50 ffi::OsStr,
51 fmt::Debug,
52 hash::Hash,
53 mem,
54 ops::{DerefMut, Range},
55 path::{Path, PathBuf},
56 pin::Pin,
57 str,
58 sync::{
59 Arc, LazyLock,
60 atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
61 },
62};
63use syntax_map::{QueryCursorHandle, SyntaxSnapshot};
64use task::RunnableTag;
65pub use task_context::{ContextLocation, ContextProvider, RunnableRange};
66pub use text_diff::{
67 DiffOptions, apply_diff_patch, line_diff, text_diff, text_diff_with_options, unified_diff,
68};
69use theme::SyntaxTheme;
70pub use toolchain::{
71 LanguageToolchainStore, LocalLanguageToolchainStore, Toolchain, ToolchainList, ToolchainLister,
72};
73use tree_sitter::{self, Query, QueryCursor, WasmStore, wasmtime};
74use util::serde::default_true;
75
76pub use buffer::Operation;
77pub use buffer::*;
78pub use diagnostic_set::{DiagnosticEntry, DiagnosticGroup};
79pub use language_registry::{
80 AvailableLanguage, BinaryStatus, LanguageNotFound, LanguageQueries, LanguageRegistry,
81 QUERY_FILENAME_PREFIXES,
82};
83pub use lsp::{LanguageServerId, LanguageServerName};
84pub use outline::*;
85pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer, ToTreeSitterPoint, TreeSitterOptions};
86pub use text::{AnchorRangeExt, LineEnding};
87pub use tree_sitter::{Node, Parser, Tree, TreeCursor};
88
89/// Initializes the `language` crate.
90///
91/// This should be called before making use of items from the create.
92pub fn init(cx: &mut App) {
93 language_settings::init(cx);
94}
95
96static QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Mutex::new(vec![]);
97static PARSERS: Mutex<Vec<Parser>> = Mutex::new(vec![]);
98
99pub fn with_parser<F, R>(func: F) -> R
100where
101 F: FnOnce(&mut Parser) -> R,
102{
103 let mut parser = PARSERS.lock().pop().unwrap_or_else(|| {
104 let mut parser = Parser::new();
105 parser
106 .set_wasm_store(WasmStore::new(&WASM_ENGINE).unwrap())
107 .unwrap();
108 parser
109 });
110 parser.set_included_ranges(&[]).unwrap();
111 let result = func(&mut parser);
112 PARSERS.lock().push(parser);
113 result
114}
115
116pub fn with_query_cursor<F, R>(func: F) -> R
117where
118 F: FnOnce(&mut QueryCursor) -> R,
119{
120 let mut cursor = QueryCursorHandle::new();
121 func(cursor.deref_mut())
122}
123
124static NEXT_LANGUAGE_ID: AtomicUsize = AtomicUsize::new(0);
125static NEXT_GRAMMAR_ID: AtomicUsize = AtomicUsize::new(0);
126static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
127 wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
128});
129
130/// A shared grammar for plain text, exposed for reuse by downstream crates.
131pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
132 Arc::new(Language::new(
133 LanguageConfig {
134 name: "Plain Text".into(),
135 soft_wrap: Some(SoftWrap::EditorWidth),
136 matcher: LanguageMatcher {
137 path_suffixes: vec!["txt".to_owned()],
138 first_line_pattern: None,
139 },
140 ..Default::default()
141 },
142 None,
143 ))
144});
145
146/// Types that represent a position in a buffer, and can be converted into
147/// an LSP position, to send to a language server.
148pub trait ToLspPosition {
149 /// Converts the value into an LSP position.
150 fn to_lsp_position(self) -> lsp::Position;
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Hash)]
154pub struct Location {
155 pub buffer: Entity<Buffer>,
156 pub range: Range<Anchor>,
157}
158
159/// Represents a Language Server, with certain cached sync properties.
160/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
161/// once at startup, and caches the results.
162pub struct CachedLspAdapter {
163 pub name: LanguageServerName,
164 pub disk_based_diagnostic_sources: Vec<String>,
165 pub disk_based_diagnostics_progress_token: Option<String>,
166 language_ids: HashMap<LanguageName, String>,
167 pub adapter: Arc<dyn LspAdapter>,
168 pub reinstall_attempt_count: AtomicU64,
169 cached_binary: futures::lock::Mutex<Option<LanguageServerBinary>>,
170}
171
172impl Debug for CachedLspAdapter {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 f.debug_struct("CachedLspAdapter")
175 .field("name", &self.name)
176 .field(
177 "disk_based_diagnostic_sources",
178 &self.disk_based_diagnostic_sources,
179 )
180 .field(
181 "disk_based_diagnostics_progress_token",
182 &self.disk_based_diagnostics_progress_token,
183 )
184 .field("language_ids", &self.language_ids)
185 .field("reinstall_attempt_count", &self.reinstall_attempt_count)
186 .finish_non_exhaustive()
187 }
188}
189
190impl CachedLspAdapter {
191 pub fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
192 let name = adapter.name();
193 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
194 let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
195 let language_ids = adapter.language_ids();
196
197 Arc::new(CachedLspAdapter {
198 name,
199 disk_based_diagnostic_sources,
200 disk_based_diagnostics_progress_token,
201 language_ids,
202 adapter,
203 cached_binary: Default::default(),
204 reinstall_attempt_count: AtomicU64::new(0),
205 })
206 }
207
208 pub fn name(&self) -> LanguageServerName {
209 self.adapter.name()
210 }
211
212 pub async fn get_language_server_command(
213 self: Arc<Self>,
214 delegate: Arc<dyn LspAdapterDelegate>,
215 toolchains: Option<Toolchain>,
216 binary_options: LanguageServerBinaryOptions,
217 cx: &mut AsyncApp,
218 ) -> Result<LanguageServerBinary> {
219 let cached_binary = self.cached_binary.lock().await;
220 self.adapter
221 .clone()
222 .get_language_server_command(delegate, toolchains, binary_options, cached_binary, cx)
223 .await
224 }
225
226 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
227 self.adapter.code_action_kinds()
228 }
229
230 pub fn process_diagnostics(
231 &self,
232 params: &mut lsp::PublishDiagnosticsParams,
233 server_id: LanguageServerId,
234 existing_diagnostics: Option<&'_ Buffer>,
235 ) {
236 self.adapter
237 .process_diagnostics(params, server_id, existing_diagnostics)
238 }
239
240 pub fn retain_old_diagnostic(&self, previous_diagnostic: &Diagnostic, cx: &App) -> bool {
241 self.adapter.retain_old_diagnostic(previous_diagnostic, cx)
242 }
243
244 pub fn underline_diagnostic(&self, diagnostic: &lsp::Diagnostic) -> bool {
245 self.adapter.underline_diagnostic(diagnostic)
246 }
247
248 pub fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
249 self.adapter.diagnostic_message_to_markdown(message)
250 }
251
252 pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
253 self.adapter.process_completions(completion_items).await
254 }
255
256 pub async fn labels_for_completions(
257 &self,
258 completion_items: &[lsp::CompletionItem],
259 language: &Arc<Language>,
260 ) -> Result<Vec<Option<CodeLabel>>> {
261 self.adapter
262 .clone()
263 .labels_for_completions(completion_items, language)
264 .await
265 }
266
267 pub async fn labels_for_symbols(
268 &self,
269 symbols: &[(String, lsp::SymbolKind)],
270 language: &Arc<Language>,
271 ) -> Result<Vec<Option<CodeLabel>>> {
272 self.adapter
273 .clone()
274 .labels_for_symbols(symbols, language)
275 .await
276 }
277
278 pub fn language_id(&self, language_name: &LanguageName) -> String {
279 self.language_ids
280 .get(language_name)
281 .cloned()
282 .unwrap_or_else(|| language_name.lsp_id())
283 }
284}
285
286/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
287// e.g. to display a notification or fetch data from the web.
288#[async_trait]
289pub trait LspAdapterDelegate: Send + Sync {
290 fn show_notification(&self, message: &str, cx: &mut App);
291 fn http_client(&self) -> Arc<dyn HttpClient>;
292 fn worktree_id(&self) -> WorktreeId;
293 fn worktree_root_path(&self) -> &Path;
294 fn update_status(&self, language: LanguageServerName, status: BinaryStatus);
295 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>>;
296 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>>;
297
298 async fn npm_package_installed_version(
299 &self,
300 package_name: &str,
301 ) -> Result<Option<(PathBuf, String)>>;
302 async fn which(&self, command: &OsStr) -> Option<PathBuf>;
303 async fn shell_env(&self) -> HashMap<String, String>;
304 async fn read_text_file(&self, path: PathBuf) -> Result<String>;
305 async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
306}
307
308#[async_trait(?Send)]
309pub trait LspAdapter: 'static + Send + Sync {
310 fn name(&self) -> LanguageServerName;
311
312 fn get_language_server_command<'a>(
313 self: Arc<Self>,
314 delegate: Arc<dyn LspAdapterDelegate>,
315 toolchains: Option<Toolchain>,
316 binary_options: LanguageServerBinaryOptions,
317 mut cached_binary: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
318 cx: &'a mut AsyncApp,
319 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
320 async move {
321 // First we check whether the adapter can give us a user-installed binary.
322 // If so, we do *not* want to cache that, because each worktree might give us a different
323 // binary:
324 //
325 // worktree 1: user-installed at `.bin/gopls`
326 // worktree 2: user-installed at `~/bin/gopls`
327 // worktree 3: no gopls found in PATH -> fallback to Zed installation
328 //
329 // We only want to cache when we fall back to the global one,
330 // because we don't want to download and overwrite our global one
331 // for each worktree we might have open.
332 if binary_options.allow_path_lookup
333 && let Some(binary) = self.check_if_user_installed(delegate.as_ref(), toolchains, cx).await {
334 log::debug!(
335 "found user-installed language server for {}. path: {:?}, arguments: {:?}",
336 self.name().0,
337 binary.path,
338 binary.arguments
339 );
340 return Ok(binary);
341 }
342
343 anyhow::ensure!(binary_options.allow_binary_download, "downloading language servers disabled");
344
345 if let Some(cached_binary) = cached_binary.as_ref() {
346 return Ok(cached_binary.clone());
347 }
348
349 let Some(container_dir) = delegate.language_server_download_dir(&self.name()).await else {
350 anyhow::bail!("no language server download dir defined")
351 };
352
353 let mut binary = try_fetch_server_binary(self.as_ref(), &delegate, container_dir.to_path_buf(), cx).await;
354
355 if let Err(error) = binary.as_ref() {
356 if let Some(prev_downloaded_binary) = self
357 .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
358 .await
359 {
360 log::info!(
361 "failed to fetch newest version of language server {:?}. error: {:?}, falling back to using {:?}",
362 self.name(),
363 error,
364 prev_downloaded_binary.path
365 );
366 binary = Ok(prev_downloaded_binary);
367 } else {
368 delegate.update_status(
369 self.name(),
370 BinaryStatus::Failed {
371 error: format!("{error:?}"),
372 },
373 );
374 }
375 }
376
377 if let Ok(binary) = &binary {
378 *cached_binary = Some(binary.clone());
379 }
380
381 binary
382 }
383 .boxed_local()
384 }
385
386 async fn check_if_user_installed(
387 &self,
388 _: &dyn LspAdapterDelegate,
389 _: Option<Toolchain>,
390 _: &AsyncApp,
391 ) -> Option<LanguageServerBinary> {
392 None
393 }
394
395 async fn fetch_latest_server_version(
396 &self,
397 delegate: &dyn LspAdapterDelegate,
398 ) -> Result<Box<dyn 'static + Send + Any>>;
399
400 fn will_fetch_server(
401 &self,
402 _: &Arc<dyn LspAdapterDelegate>,
403 _: &mut AsyncApp,
404 ) -> Option<Task<Result<()>>> {
405 None
406 }
407
408 async fn check_if_version_installed(
409 &self,
410 _version: &(dyn 'static + Send + Any),
411 _container_dir: &PathBuf,
412 _delegate: &dyn LspAdapterDelegate,
413 ) -> Option<LanguageServerBinary> {
414 None
415 }
416
417 async fn fetch_server_binary(
418 &self,
419 latest_version: Box<dyn 'static + Send + Any>,
420 container_dir: PathBuf,
421 delegate: &dyn LspAdapterDelegate,
422 ) -> Result<LanguageServerBinary>;
423
424 async fn cached_server_binary(
425 &self,
426 container_dir: PathBuf,
427 delegate: &dyn LspAdapterDelegate,
428 ) -> Option<LanguageServerBinary>;
429
430 fn process_diagnostics(
431 &self,
432 _: &mut lsp::PublishDiagnosticsParams,
433 _: LanguageServerId,
434 _: Option<&'_ Buffer>,
435 ) {
436 }
437
438 /// When processing new `lsp::PublishDiagnosticsParams` diagnostics, whether to retain previous one(s) or not.
439 fn retain_old_diagnostic(&self, _previous_diagnostic: &Diagnostic, _cx: &App) -> bool {
440 false
441 }
442
443 /// Whether to underline a given diagnostic or not, when rendering in the editor.
444 ///
445 /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnosticTag
446 /// states that
447 /// > Clients are allowed to render diagnostics with this tag faded out instead of having an error squiggle.
448 /// for the unnecessary diagnostics, so do not underline them.
449 fn underline_diagnostic(&self, _diagnostic: &lsp::Diagnostic) -> bool {
450 true
451 }
452
453 /// Post-processes completions provided by the language server.
454 async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
455
456 fn diagnostic_message_to_markdown(&self, _message: &str) -> Option<String> {
457 None
458 }
459
460 async fn labels_for_completions(
461 self: Arc<Self>,
462 completions: &[lsp::CompletionItem],
463 language: &Arc<Language>,
464 ) -> Result<Vec<Option<CodeLabel>>> {
465 let mut labels = Vec::new();
466 for (ix, completion) in completions.iter().enumerate() {
467 let label = self.label_for_completion(completion, language).await;
468 if let Some(label) = label {
469 labels.resize(ix + 1, None);
470 *labels.last_mut().unwrap() = Some(label);
471 }
472 }
473 Ok(labels)
474 }
475
476 async fn label_for_completion(
477 &self,
478 _: &lsp::CompletionItem,
479 _: &Arc<Language>,
480 ) -> Option<CodeLabel> {
481 None
482 }
483
484 async fn labels_for_symbols(
485 self: Arc<Self>,
486 symbols: &[(String, lsp::SymbolKind)],
487 language: &Arc<Language>,
488 ) -> Result<Vec<Option<CodeLabel>>> {
489 let mut labels = Vec::new();
490 for (ix, (name, kind)) in symbols.iter().enumerate() {
491 let label = self.label_for_symbol(name, *kind, language).await;
492 if let Some(label) = label {
493 labels.resize(ix + 1, None);
494 *labels.last_mut().unwrap() = Some(label);
495 }
496 }
497 Ok(labels)
498 }
499
500 async fn label_for_symbol(
501 &self,
502 _: &str,
503 _: lsp::SymbolKind,
504 _: &Arc<Language>,
505 ) -> Option<CodeLabel> {
506 None
507 }
508
509 /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
510 async fn initialization_options(
511 self: Arc<Self>,
512 _: &dyn Fs,
513 _: &Arc<dyn LspAdapterDelegate>,
514 ) -> Result<Option<Value>> {
515 Ok(None)
516 }
517
518 async fn workspace_configuration(
519 self: Arc<Self>,
520 _: &dyn Fs,
521 _: &Arc<dyn LspAdapterDelegate>,
522 _: Option<Toolchain>,
523 _cx: &mut AsyncApp,
524 ) -> Result<Value> {
525 Ok(serde_json::json!({}))
526 }
527
528 async fn additional_initialization_options(
529 self: Arc<Self>,
530 _target_language_server_id: LanguageServerName,
531 _: &dyn Fs,
532 _: &Arc<dyn LspAdapterDelegate>,
533 ) -> Result<Option<Value>> {
534 Ok(None)
535 }
536
537 async fn additional_workspace_configuration(
538 self: Arc<Self>,
539 _target_language_server_id: LanguageServerName,
540 _: &dyn Fs,
541 _: &Arc<dyn LspAdapterDelegate>,
542 _cx: &mut AsyncApp,
543 ) -> Result<Option<Value>> {
544 Ok(None)
545 }
546
547 /// Returns a list of code actions supported by a given LspAdapter
548 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
549 None
550 }
551
552 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
553 Default::default()
554 }
555
556 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
557 None
558 }
559
560 fn language_ids(&self) -> HashMap<LanguageName, String> {
561 HashMap::default()
562 }
563
564 /// Support custom initialize params.
565 fn prepare_initialize_params(
566 &self,
567 original: InitializeParams,
568 _: &App,
569 ) -> Result<InitializeParams> {
570 Ok(original)
571 }
572
573 /// Method only implemented by the default JSON language server adapter.
574 /// Used to provide dynamic reloading of the JSON schemas used to
575 /// provide autocompletion and diagnostics in Zed setting and keybind
576 /// files
577 fn is_primary_zed_json_schema_adapter(&self) -> bool {
578 false
579 }
580
581 /// Method only implemented by the default JSON language server adapter.
582 /// Used to clear the cache of JSON schemas that are used to provide
583 /// autocompletion and diagnostics in Zed settings and keybinds files.
584 /// Should not be called unless the callee is sure that
585 /// `Self::is_primary_zed_json_schema_adapter` returns `true`
586 async fn clear_zed_json_schema_cache(&self) {
587 unreachable!(
588 "Not implemented for this adapter. This method should only be called on the default JSON language server adapter"
589 );
590 }
591}
592
593async fn try_fetch_server_binary<L: LspAdapter + 'static + Send + Sync + ?Sized>(
594 adapter: &L,
595 delegate: &Arc<dyn LspAdapterDelegate>,
596 container_dir: PathBuf,
597 cx: &mut AsyncApp,
598) -> Result<LanguageServerBinary> {
599 if let Some(task) = adapter.will_fetch_server(delegate, cx) {
600 task.await?;
601 }
602
603 let name = adapter.name();
604 log::debug!("fetching latest version of language server {:?}", name.0);
605 delegate.update_status(name.clone(), BinaryStatus::CheckingForUpdate);
606
607 let latest_version = adapter
608 .fetch_latest_server_version(delegate.as_ref())
609 .await?;
610
611 if let Some(binary) = adapter
612 .check_if_version_installed(latest_version.as_ref(), &container_dir, delegate.as_ref())
613 .await
614 {
615 log::debug!("language server {:?} is already installed", name.0);
616 delegate.update_status(name.clone(), BinaryStatus::None);
617 Ok(binary)
618 } else {
619 log::info!("downloading language server {:?}", name.0);
620 delegate.update_status(adapter.name(), BinaryStatus::Downloading);
621 let binary = adapter
622 .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
623 .await;
624
625 delegate.update_status(name.clone(), BinaryStatus::None);
626 binary
627 }
628}
629
630#[derive(Clone, Debug, Default, PartialEq, Eq)]
631pub struct CodeLabel {
632 /// The text to display.
633 pub text: String,
634 /// Syntax highlighting runs.
635 pub runs: Vec<(Range<usize>, HighlightId)>,
636 /// The portion of the text that should be used in fuzzy filtering.
637 pub filter_range: Range<usize>,
638}
639
640#[derive(Clone, Deserialize, JsonSchema)]
641pub struct LanguageConfig {
642 /// Human-readable name of the language.
643 pub name: LanguageName,
644 /// The name of this language for a Markdown code fence block
645 pub code_fence_block_name: Option<Arc<str>>,
646 // The name of the grammar in a WASM bundle (experimental).
647 pub grammar: Option<Arc<str>>,
648 /// The criteria for matching this language to a given file.
649 #[serde(flatten)]
650 pub matcher: LanguageMatcher,
651 /// List of bracket types in a language.
652 #[serde(default)]
653 pub brackets: BracketPairConfig,
654 /// If set to true, auto indentation uses last non empty line to determine
655 /// the indentation level for a new line.
656 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
657 pub auto_indent_using_last_non_empty_line: bool,
658 // Whether indentation of pasted content should be adjusted based on the context.
659 #[serde(default)]
660 pub auto_indent_on_paste: Option<bool>,
661 /// A regex that is used to determine whether the indentation level should be
662 /// increased in the following line.
663 #[serde(default, deserialize_with = "deserialize_regex")]
664 #[schemars(schema_with = "regex_json_schema")]
665 pub increase_indent_pattern: Option<Regex>,
666 /// A regex that is used to determine whether the indentation level should be
667 /// decreased in the following line.
668 #[serde(default, deserialize_with = "deserialize_regex")]
669 #[schemars(schema_with = "regex_json_schema")]
670 pub decrease_indent_pattern: Option<Regex>,
671 /// A list of rules for decreasing indentation. Each rule pairs a regex with a set of valid
672 /// "block-starting" tokens. When a line matches a pattern, its indentation is aligned with
673 /// the most recent line that began with a corresponding token. This enables context-aware
674 /// outdenting, like aligning an `else` with its `if`.
675 #[serde(default)]
676 pub decrease_indent_patterns: Vec<DecreaseIndentConfig>,
677 /// A list of characters that trigger the automatic insertion of a closing
678 /// bracket when they immediately precede the point where an opening
679 /// bracket is inserted.
680 #[serde(default)]
681 pub autoclose_before: String,
682 /// A placeholder used internally by Semantic Index.
683 #[serde(default)]
684 pub collapsed_placeholder: String,
685 /// A line comment string that is inserted in e.g. `toggle comments` action.
686 /// A language can have multiple flavours of line comments. All of the provided line comments are
687 /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
688 #[serde(default)]
689 pub line_comments: Vec<Arc<str>>,
690 /// Delimiters and configuration for recognizing and formatting block comments.
691 #[serde(default)]
692 pub block_comment: Option<BlockCommentConfig>,
693 /// Delimiters and configuration for recognizing and formatting documentation comments.
694 #[serde(default, alias = "documentation")]
695 pub documentation_comment: Option<BlockCommentConfig>,
696 /// A list of additional regex patterns that should be treated as prefixes
697 /// for creating boundaries during rewrapping, ensuring content from one
698 /// prefixed section doesn't merge with another (e.g., markdown list items).
699 /// By default, Zed treats as paragraph and comment prefixes as boundaries.
700 #[serde(default, deserialize_with = "deserialize_regex_vec")]
701 #[schemars(schema_with = "regex_vec_json_schema")]
702 pub rewrap_prefixes: Vec<Regex>,
703 /// A list of language servers that are allowed to run on subranges of a given language.
704 #[serde(default)]
705 pub scope_opt_in_language_servers: Vec<LanguageServerName>,
706 #[serde(default)]
707 pub overrides: HashMap<String, LanguageConfigOverride>,
708 /// A list of characters that Zed should treat as word characters for the
709 /// purpose of features that operate on word boundaries, like 'move to next word end'
710 /// or a whole-word search in buffer search.
711 #[serde(default)]
712 pub word_characters: HashSet<char>,
713 /// Whether to indent lines using tab characters, as opposed to multiple
714 /// spaces.
715 #[serde(default)]
716 pub hard_tabs: Option<bool>,
717 /// How many columns a tab should occupy.
718 #[serde(default)]
719 pub tab_size: Option<NonZeroU32>,
720 /// How to soft-wrap long lines of text.
721 #[serde(default)]
722 pub soft_wrap: Option<SoftWrap>,
723 /// When set, selections can be wrapped using prefix/suffix pairs on both sides.
724 #[serde(default)]
725 pub wrap_characters: Option<WrapCharactersConfig>,
726 /// The name of a Prettier parser that will be used for this language when no file path is available.
727 /// If there's a parser name in the language settings, that will be used instead.
728 #[serde(default)]
729 pub prettier_parser_name: Option<String>,
730 /// If true, this language is only for syntax highlighting via an injection into other
731 /// languages, but should not appear to the user as a distinct language.
732 #[serde(default)]
733 pub hidden: bool,
734 /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
735 #[serde(default)]
736 pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
737 /// A list of characters that Zed should treat as word characters for completion queries.
738 #[serde(default)]
739 pub completion_query_characters: HashSet<char>,
740 /// A list of preferred debuggers for this language.
741 #[serde(default)]
742 pub debuggers: IndexSet<SharedString>,
743}
744
745#[derive(Clone, Debug, Deserialize, Default, JsonSchema)]
746pub struct DecreaseIndentConfig {
747 #[serde(default, deserialize_with = "deserialize_regex")]
748 #[schemars(schema_with = "regex_json_schema")]
749 pub pattern: Option<Regex>,
750 #[serde(default)]
751 pub valid_after: Vec<String>,
752}
753
754#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
755pub struct LanguageMatcher {
756 /// Given a list of `LanguageConfig`'s, the language of a file can be determined based on the path extension matching any of the `path_suffixes`.
757 #[serde(default)]
758 pub path_suffixes: Vec<String>,
759 /// A regex pattern that determines whether the language should be assigned to a file or not.
760 #[serde(
761 default,
762 serialize_with = "serialize_regex",
763 deserialize_with = "deserialize_regex"
764 )]
765 #[schemars(schema_with = "regex_json_schema")]
766 pub first_line_pattern: Option<Regex>,
767}
768
769/// The configuration for JSX tag auto-closing.
770#[derive(Clone, Deserialize, JsonSchema)]
771pub struct JsxTagAutoCloseConfig {
772 /// The name of the node for a opening tag
773 pub open_tag_node_name: String,
774 /// The name of the node for an closing tag
775 pub close_tag_node_name: String,
776 /// The name of the node for a complete element with children for open and close tags
777 pub jsx_element_node_name: String,
778 /// The name of the node found within both opening and closing
779 /// tags that describes the tag name
780 pub tag_name_node_name: String,
781 /// Alternate Node names for tag names.
782 /// Specifically needed as TSX represents the name in `<Foo.Bar>`
783 /// as `member_expression` rather than `identifier` as usual
784 #[serde(default)]
785 pub tag_name_node_name_alternates: Vec<String>,
786 /// Some grammars are smart enough to detect a closing tag
787 /// that is not valid i.e. doesn't match it's corresponding
788 /// opening tag or does not have a corresponding opening tag
789 /// This should be set to the name of the node for invalid
790 /// closing tags if the grammar contains such a node, otherwise
791 /// detecting already closed tags will not work properly
792 #[serde(default)]
793 pub erroneous_close_tag_node_name: Option<String>,
794 /// See above for erroneous_close_tag_node_name for details
795 /// This should be set if the node used for the tag name
796 /// within erroneous closing tags is different from the
797 /// normal tag name node name
798 #[serde(default)]
799 pub erroneous_close_tag_name_node_name: Option<String>,
800}
801
802/// The configuration for block comments for this language.
803#[derive(Clone, Debug, JsonSchema, PartialEq)]
804pub struct BlockCommentConfig {
805 /// A start tag of block comment.
806 pub start: Arc<str>,
807 /// A end tag of block comment.
808 pub end: Arc<str>,
809 /// A character to add as a prefix when a new line is added to a block comment.
810 pub prefix: Arc<str>,
811 /// A indent to add for prefix and end line upon new line.
812 pub tab_size: u32,
813}
814
815impl<'de> Deserialize<'de> for BlockCommentConfig {
816 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
817 where
818 D: Deserializer<'de>,
819 {
820 #[derive(Deserialize)]
821 #[serde(untagged)]
822 enum BlockCommentConfigHelper {
823 New {
824 start: Arc<str>,
825 end: Arc<str>,
826 prefix: Arc<str>,
827 tab_size: u32,
828 },
829 Old([Arc<str>; 2]),
830 }
831
832 match BlockCommentConfigHelper::deserialize(deserializer)? {
833 BlockCommentConfigHelper::New {
834 start,
835 end,
836 prefix,
837 tab_size,
838 } => Ok(BlockCommentConfig {
839 start,
840 end,
841 prefix,
842 tab_size,
843 }),
844 BlockCommentConfigHelper::Old([start, end]) => Ok(BlockCommentConfig {
845 start,
846 end,
847 prefix: "".into(),
848 tab_size: 0,
849 }),
850 }
851 }
852}
853
854/// Represents a language for the given range. Some languages (e.g. HTML)
855/// interleave several languages together, thus a single buffer might actually contain
856/// several nested scopes.
857#[derive(Clone, Debug)]
858pub struct LanguageScope {
859 language: Arc<Language>,
860 override_id: Option<u32>,
861}
862
863#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
864pub struct LanguageConfigOverride {
865 #[serde(default)]
866 pub line_comments: Override<Vec<Arc<str>>>,
867 #[serde(default)]
868 pub block_comment: Override<BlockCommentConfig>,
869 #[serde(skip)]
870 pub disabled_bracket_ixs: Vec<u16>,
871 #[serde(default)]
872 pub word_characters: Override<HashSet<char>>,
873 #[serde(default)]
874 pub completion_query_characters: Override<HashSet<char>>,
875 #[serde(default)]
876 pub opt_into_language_servers: Vec<LanguageServerName>,
877 #[serde(default)]
878 pub prefer_label_for_snippet: Option<bool>,
879}
880
881#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
882#[serde(untagged)]
883pub enum Override<T> {
884 Remove { remove: bool },
885 Set(T),
886}
887
888impl<T> Default for Override<T> {
889 fn default() -> Self {
890 Override::Remove { remove: false }
891 }
892}
893
894impl<T> Override<T> {
895 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
896 match this {
897 Some(Self::Set(value)) => Some(value),
898 Some(Self::Remove { remove: true }) => None,
899 Some(Self::Remove { remove: false }) | None => original,
900 }
901 }
902}
903
904impl Default for LanguageConfig {
905 fn default() -> Self {
906 Self {
907 name: LanguageName::new(""),
908 code_fence_block_name: None,
909 grammar: None,
910 matcher: LanguageMatcher::default(),
911 brackets: Default::default(),
912 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
913 auto_indent_on_paste: None,
914 increase_indent_pattern: Default::default(),
915 decrease_indent_pattern: Default::default(),
916 decrease_indent_patterns: Default::default(),
917 autoclose_before: Default::default(),
918 line_comments: Default::default(),
919 block_comment: Default::default(),
920 documentation_comment: Default::default(),
921 rewrap_prefixes: Default::default(),
922 scope_opt_in_language_servers: Default::default(),
923 overrides: Default::default(),
924 word_characters: Default::default(),
925 collapsed_placeholder: Default::default(),
926 hard_tabs: None,
927 tab_size: None,
928 soft_wrap: None,
929 wrap_characters: None,
930 prettier_parser_name: None,
931 hidden: false,
932 jsx_tag_auto_close: None,
933 completion_query_characters: Default::default(),
934 debuggers: Default::default(),
935 }
936 }
937}
938
939#[derive(Clone, Debug, Deserialize, JsonSchema)]
940pub struct WrapCharactersConfig {
941 /// Opening token split into a prefix and suffix. The first caret goes
942 /// after the prefix (i.e., between prefix and suffix).
943 pub start_prefix: String,
944 pub start_suffix: String,
945 /// Closing token split into a prefix and suffix. The second caret goes
946 /// after the prefix (i.e., between prefix and suffix).
947 pub end_prefix: String,
948 pub end_suffix: String,
949}
950
951fn auto_indent_using_last_non_empty_line_default() -> bool {
952 true
953}
954
955fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
956 let source = Option::<String>::deserialize(d)?;
957 if let Some(source) = source {
958 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
959 } else {
960 Ok(None)
961 }
962}
963
964fn regex_json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
965 json_schema!({
966 "type": "string"
967 })
968}
969
970fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
971where
972 S: Serializer,
973{
974 match regex {
975 Some(regex) => serializer.serialize_str(regex.as_str()),
976 None => serializer.serialize_none(),
977 }
978}
979
980fn deserialize_regex_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Regex>, D::Error> {
981 let sources = Vec::<String>::deserialize(d)?;
982 sources
983 .into_iter()
984 .map(|source| regex::Regex::new(&source))
985 .collect::<Result<_, _>>()
986 .map_err(de::Error::custom)
987}
988
989fn regex_vec_json_schema(_: &mut SchemaGenerator) -> schemars::Schema {
990 json_schema!({
991 "type": "array",
992 "items": { "type": "string" }
993 })
994}
995
996#[doc(hidden)]
997#[cfg(any(test, feature = "test-support"))]
998pub struct FakeLspAdapter {
999 pub name: &'static str,
1000 pub initialization_options: Option<Value>,
1001 pub prettier_plugins: Vec<&'static str>,
1002 pub disk_based_diagnostics_progress_token: Option<String>,
1003 pub disk_based_diagnostics_sources: Vec<String>,
1004 pub language_server_binary: LanguageServerBinary,
1005
1006 pub capabilities: lsp::ServerCapabilities,
1007 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
1008 pub label_for_completion: Option<
1009 Box<
1010 dyn 'static
1011 + Send
1012 + Sync
1013 + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
1014 >,
1015 >,
1016}
1017
1018/// Configuration of handling bracket pairs for a given language.
1019///
1020/// This struct includes settings for defining which pairs of characters are considered brackets and
1021/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
1022#[derive(Clone, Debug, Default, JsonSchema)]
1023#[schemars(with = "Vec::<BracketPairContent>")]
1024pub struct BracketPairConfig {
1025 /// A list of character pairs that should be treated as brackets in the context of a given language.
1026 pub pairs: Vec<BracketPair>,
1027 /// A list of tree-sitter scopes for which a given bracket should not be active.
1028 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
1029 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
1030}
1031
1032impl BracketPairConfig {
1033 pub fn is_closing_brace(&self, c: char) -> bool {
1034 self.pairs.iter().any(|pair| pair.end.starts_with(c))
1035 }
1036}
1037
1038#[derive(Deserialize, JsonSchema)]
1039pub struct BracketPairContent {
1040 #[serde(flatten)]
1041 pub bracket_pair: BracketPair,
1042 #[serde(default)]
1043 pub not_in: Vec<String>,
1044}
1045
1046impl<'de> Deserialize<'de> for BracketPairConfig {
1047 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1048 where
1049 D: Deserializer<'de>,
1050 {
1051 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
1052 let (brackets, disabled_scopes_by_bracket_ix) = result
1053 .into_iter()
1054 .map(|entry| (entry.bracket_pair, entry.not_in))
1055 .unzip();
1056
1057 Ok(BracketPairConfig {
1058 pairs: brackets,
1059 disabled_scopes_by_bracket_ix,
1060 })
1061 }
1062}
1063
1064/// Describes a single bracket pair and how an editor should react to e.g. inserting
1065/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
1066#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
1067pub struct BracketPair {
1068 /// Starting substring for a bracket.
1069 pub start: String,
1070 /// Ending substring for a bracket.
1071 pub end: String,
1072 /// True if `end` should be automatically inserted right after `start` characters.
1073 pub close: bool,
1074 /// True if selected text should be surrounded by `start` and `end` characters.
1075 #[serde(default = "default_true")]
1076 pub surround: bool,
1077 /// True if an extra newline should be inserted while the cursor is in the middle
1078 /// of that bracket pair.
1079 pub newline: bool,
1080}
1081
1082#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1083pub struct LanguageId(usize);
1084
1085impl LanguageId {
1086 pub(crate) fn new() -> Self {
1087 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
1088 }
1089}
1090
1091pub struct Language {
1092 pub(crate) id: LanguageId,
1093 pub(crate) config: LanguageConfig,
1094 pub(crate) grammar: Option<Arc<Grammar>>,
1095 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1096 pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1097 pub(crate) manifest_name: Option<ManifestName>,
1098}
1099
1100#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1101pub struct GrammarId(pub usize);
1102
1103impl GrammarId {
1104 pub(crate) fn new() -> Self {
1105 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1106 }
1107}
1108
1109pub struct Grammar {
1110 id: GrammarId,
1111 pub ts_language: tree_sitter::Language,
1112 pub(crate) error_query: Option<Query>,
1113 pub(crate) highlights_query: Option<Query>,
1114 pub(crate) brackets_config: Option<BracketsConfig>,
1115 pub(crate) redactions_config: Option<RedactionConfig>,
1116 pub(crate) runnable_config: Option<RunnableConfig>,
1117 pub(crate) indents_config: Option<IndentConfig>,
1118 pub outline_config: Option<OutlineConfig>,
1119 pub text_object_config: Option<TextObjectConfig>,
1120 pub embedding_config: Option<EmbeddingConfig>,
1121 pub(crate) injection_config: Option<InjectionConfig>,
1122 pub(crate) override_config: Option<OverrideConfig>,
1123 pub(crate) debug_variables_config: Option<DebugVariablesConfig>,
1124 pub(crate) highlight_map: Mutex<HighlightMap>,
1125}
1126
1127struct IndentConfig {
1128 query: Query,
1129 indent_capture_ix: u32,
1130 start_capture_ix: Option<u32>,
1131 end_capture_ix: Option<u32>,
1132 outdent_capture_ix: Option<u32>,
1133 suffixed_start_captures: HashMap<u32, SharedString>,
1134}
1135
1136pub struct OutlineConfig {
1137 pub query: Query,
1138 pub item_capture_ix: u32,
1139 pub name_capture_ix: u32,
1140 pub context_capture_ix: Option<u32>,
1141 pub extra_context_capture_ix: Option<u32>,
1142 pub open_capture_ix: Option<u32>,
1143 pub close_capture_ix: Option<u32>,
1144 pub annotation_capture_ix: Option<u32>,
1145}
1146
1147#[derive(Debug, Clone, Copy, PartialEq)]
1148pub enum DebuggerTextObject {
1149 Variable,
1150 Scope,
1151}
1152
1153impl DebuggerTextObject {
1154 pub fn from_capture_name(name: &str) -> Option<DebuggerTextObject> {
1155 match name {
1156 "debug-variable" => Some(DebuggerTextObject::Variable),
1157 "debug-scope" => Some(DebuggerTextObject::Scope),
1158 _ => None,
1159 }
1160 }
1161}
1162
1163#[derive(Debug, Clone, Copy, PartialEq)]
1164pub enum TextObject {
1165 InsideFunction,
1166 AroundFunction,
1167 InsideClass,
1168 AroundClass,
1169 InsideComment,
1170 AroundComment,
1171}
1172
1173impl TextObject {
1174 pub fn from_capture_name(name: &str) -> Option<TextObject> {
1175 match name {
1176 "function.inside" => Some(TextObject::InsideFunction),
1177 "function.around" => Some(TextObject::AroundFunction),
1178 "class.inside" => Some(TextObject::InsideClass),
1179 "class.around" => Some(TextObject::AroundClass),
1180 "comment.inside" => Some(TextObject::InsideComment),
1181 "comment.around" => Some(TextObject::AroundComment),
1182 _ => None,
1183 }
1184 }
1185
1186 pub fn around(&self) -> Option<Self> {
1187 match self {
1188 TextObject::InsideFunction => Some(TextObject::AroundFunction),
1189 TextObject::InsideClass => Some(TextObject::AroundClass),
1190 TextObject::InsideComment => Some(TextObject::AroundComment),
1191 _ => None,
1192 }
1193 }
1194}
1195
1196pub struct TextObjectConfig {
1197 pub query: Query,
1198 pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1199}
1200
1201#[derive(Debug)]
1202pub struct EmbeddingConfig {
1203 pub query: Query,
1204 pub item_capture_ix: u32,
1205 pub name_capture_ix: Option<u32>,
1206 pub context_capture_ix: Option<u32>,
1207 pub collapse_capture_ix: Option<u32>,
1208 pub keep_capture_ix: Option<u32>,
1209}
1210
1211struct InjectionConfig {
1212 query: Query,
1213 content_capture_ix: u32,
1214 language_capture_ix: Option<u32>,
1215 patterns: Vec<InjectionPatternConfig>,
1216}
1217
1218struct RedactionConfig {
1219 pub query: Query,
1220 pub redaction_capture_ix: u32,
1221}
1222
1223#[derive(Clone, Debug, PartialEq)]
1224enum RunnableCapture {
1225 Named(SharedString),
1226 Run,
1227}
1228
1229struct RunnableConfig {
1230 pub query: Query,
1231 /// A mapping from capture indice to capture kind
1232 pub extra_captures: Vec<RunnableCapture>,
1233}
1234
1235struct OverrideConfig {
1236 query: Query,
1237 values: HashMap<u32, OverrideEntry>,
1238}
1239
1240#[derive(Debug)]
1241struct OverrideEntry {
1242 name: String,
1243 range_is_inclusive: bool,
1244 value: LanguageConfigOverride,
1245}
1246
1247#[derive(Default, Clone)]
1248struct InjectionPatternConfig {
1249 language: Option<Box<str>>,
1250 combined: bool,
1251}
1252
1253#[derive(Debug)]
1254struct BracketsConfig {
1255 query: Query,
1256 open_capture_ix: u32,
1257 close_capture_ix: u32,
1258 patterns: Vec<BracketsPatternConfig>,
1259}
1260
1261#[derive(Clone, Debug, Default)]
1262struct BracketsPatternConfig {
1263 newline_only: bool,
1264}
1265
1266pub struct DebugVariablesConfig {
1267 pub query: Query,
1268 pub objects_by_capture_ix: Vec<(u32, DebuggerTextObject)>,
1269}
1270
1271impl Language {
1272 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1273 Self::new_with_id(LanguageId::new(), config, ts_language)
1274 }
1275
1276 pub fn id(&self) -> LanguageId {
1277 self.id
1278 }
1279
1280 fn new_with_id(
1281 id: LanguageId,
1282 config: LanguageConfig,
1283 ts_language: Option<tree_sitter::Language>,
1284 ) -> Self {
1285 Self {
1286 id,
1287 config,
1288 grammar: ts_language.map(|ts_language| {
1289 Arc::new(Grammar {
1290 id: GrammarId::new(),
1291 highlights_query: None,
1292 brackets_config: None,
1293 outline_config: None,
1294 text_object_config: None,
1295 embedding_config: None,
1296 indents_config: None,
1297 injection_config: None,
1298 override_config: None,
1299 redactions_config: None,
1300 runnable_config: None,
1301 error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1302 debug_variables_config: None,
1303 ts_language,
1304 highlight_map: Default::default(),
1305 })
1306 }),
1307 context_provider: None,
1308 toolchain: None,
1309 manifest_name: None,
1310 }
1311 }
1312
1313 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1314 self.context_provider = provider;
1315 self
1316 }
1317
1318 pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1319 self.toolchain = provider;
1320 self
1321 }
1322
1323 pub fn with_manifest(mut self, name: Option<ManifestName>) -> Self {
1324 self.manifest_name = name;
1325 self
1326 }
1327 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1328 if let Some(query) = queries.highlights {
1329 self = self
1330 .with_highlights_query(query.as_ref())
1331 .context("Error loading highlights query")?;
1332 }
1333 if let Some(query) = queries.brackets {
1334 self = self
1335 .with_brackets_query(query.as_ref())
1336 .context("Error loading brackets query")?;
1337 }
1338 if let Some(query) = queries.indents {
1339 self = self
1340 .with_indents_query(query.as_ref())
1341 .context("Error loading indents query")?;
1342 }
1343 if let Some(query) = queries.outline {
1344 self = self
1345 .with_outline_query(query.as_ref())
1346 .context("Error loading outline query")?;
1347 }
1348 if let Some(query) = queries.embedding {
1349 self = self
1350 .with_embedding_query(query.as_ref())
1351 .context("Error loading embedding query")?;
1352 }
1353 if let Some(query) = queries.injections {
1354 self = self
1355 .with_injection_query(query.as_ref())
1356 .context("Error loading injection query")?;
1357 }
1358 if let Some(query) = queries.overrides {
1359 self = self
1360 .with_override_query(query.as_ref())
1361 .context("Error loading override query")?;
1362 }
1363 if let Some(query) = queries.redactions {
1364 self = self
1365 .with_redaction_query(query.as_ref())
1366 .context("Error loading redaction query")?;
1367 }
1368 if let Some(query) = queries.runnables {
1369 self = self
1370 .with_runnable_query(query.as_ref())
1371 .context("Error loading runnables query")?;
1372 }
1373 if let Some(query) = queries.text_objects {
1374 self = self
1375 .with_text_object_query(query.as_ref())
1376 .context("Error loading textobject query")?;
1377 }
1378 if let Some(query) = queries.debugger {
1379 self = self
1380 .with_debug_variables_query(query.as_ref())
1381 .context("Error loading debug variables query")?;
1382 }
1383 Ok(self)
1384 }
1385
1386 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1387 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1388 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1389 Ok(self)
1390 }
1391
1392 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1393 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1394
1395 let query = Query::new(&grammar.ts_language, source)?;
1396 let extra_captures: Vec<_> = query
1397 .capture_names()
1398 .iter()
1399 .map(|&name| match name {
1400 "run" => RunnableCapture::Run,
1401 name => RunnableCapture::Named(name.to_string().into()),
1402 })
1403 .collect();
1404
1405 grammar.runnable_config = Some(RunnableConfig {
1406 extra_captures,
1407 query,
1408 });
1409
1410 Ok(self)
1411 }
1412
1413 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1414 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1415 let query = Query::new(&grammar.ts_language, source)?;
1416 let mut item_capture_ix = None;
1417 let mut name_capture_ix = None;
1418 let mut context_capture_ix = None;
1419 let mut extra_context_capture_ix = None;
1420 let mut open_capture_ix = None;
1421 let mut close_capture_ix = None;
1422 let mut annotation_capture_ix = None;
1423 get_capture_indices(
1424 &query,
1425 &mut [
1426 ("item", &mut item_capture_ix),
1427 ("name", &mut name_capture_ix),
1428 ("context", &mut context_capture_ix),
1429 ("context.extra", &mut extra_context_capture_ix),
1430 ("open", &mut open_capture_ix),
1431 ("close", &mut close_capture_ix),
1432 ("annotation", &mut annotation_capture_ix),
1433 ],
1434 );
1435 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1436 grammar.outline_config = Some(OutlineConfig {
1437 query,
1438 item_capture_ix,
1439 name_capture_ix,
1440 context_capture_ix,
1441 extra_context_capture_ix,
1442 open_capture_ix,
1443 close_capture_ix,
1444 annotation_capture_ix,
1445 });
1446 }
1447 Ok(self)
1448 }
1449
1450 pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1451 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1452 let query = Query::new(&grammar.ts_language, source)?;
1453
1454 let mut text_objects_by_capture_ix = Vec::new();
1455 for (ix, name) in query.capture_names().iter().enumerate() {
1456 if let Some(text_object) = TextObject::from_capture_name(name) {
1457 text_objects_by_capture_ix.push((ix as u32, text_object));
1458 }
1459 }
1460
1461 grammar.text_object_config = Some(TextObjectConfig {
1462 query,
1463 text_objects_by_capture_ix,
1464 });
1465 Ok(self)
1466 }
1467
1468 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1469 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1470 let query = Query::new(&grammar.ts_language, source)?;
1471 let mut item_capture_ix = None;
1472 let mut name_capture_ix = None;
1473 let mut context_capture_ix = None;
1474 let mut collapse_capture_ix = None;
1475 let mut keep_capture_ix = None;
1476 get_capture_indices(
1477 &query,
1478 &mut [
1479 ("item", &mut item_capture_ix),
1480 ("name", &mut name_capture_ix),
1481 ("context", &mut context_capture_ix),
1482 ("keep", &mut keep_capture_ix),
1483 ("collapse", &mut collapse_capture_ix),
1484 ],
1485 );
1486 if let Some(item_capture_ix) = item_capture_ix {
1487 grammar.embedding_config = Some(EmbeddingConfig {
1488 query,
1489 item_capture_ix,
1490 name_capture_ix,
1491 context_capture_ix,
1492 collapse_capture_ix,
1493 keep_capture_ix,
1494 });
1495 }
1496 Ok(self)
1497 }
1498
1499 pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1500 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1501 let query = Query::new(&grammar.ts_language, source)?;
1502
1503 let mut objects_by_capture_ix = Vec::new();
1504 for (ix, name) in query.capture_names().iter().enumerate() {
1505 if let Some(text_object) = DebuggerTextObject::from_capture_name(name) {
1506 objects_by_capture_ix.push((ix as u32, text_object));
1507 }
1508 }
1509
1510 grammar.debug_variables_config = Some(DebugVariablesConfig {
1511 query,
1512 objects_by_capture_ix,
1513 });
1514 Ok(self)
1515 }
1516
1517 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1518 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1519 let query = Query::new(&grammar.ts_language, source)?;
1520 let mut open_capture_ix = None;
1521 let mut close_capture_ix = None;
1522 get_capture_indices(
1523 &query,
1524 &mut [
1525 ("open", &mut open_capture_ix),
1526 ("close", &mut close_capture_ix),
1527 ],
1528 );
1529 let patterns = (0..query.pattern_count())
1530 .map(|ix| {
1531 let mut config = BracketsPatternConfig::default();
1532 for setting in query.property_settings(ix) {
1533 if setting.key.as_ref() == "newline.only" {
1534 config.newline_only = true
1535 }
1536 }
1537 config
1538 })
1539 .collect();
1540 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1541 grammar.brackets_config = Some(BracketsConfig {
1542 query,
1543 open_capture_ix,
1544 close_capture_ix,
1545 patterns,
1546 });
1547 }
1548 Ok(self)
1549 }
1550
1551 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1552 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1553 let query = Query::new(&grammar.ts_language, source)?;
1554 let mut indent_capture_ix = None;
1555 let mut start_capture_ix = None;
1556 let mut end_capture_ix = None;
1557 let mut outdent_capture_ix = None;
1558 get_capture_indices(
1559 &query,
1560 &mut [
1561 ("indent", &mut indent_capture_ix),
1562 ("start", &mut start_capture_ix),
1563 ("end", &mut end_capture_ix),
1564 ("outdent", &mut outdent_capture_ix),
1565 ],
1566 );
1567
1568 let mut suffixed_start_captures = HashMap::default();
1569 for (ix, name) in query.capture_names().iter().enumerate() {
1570 if let Some(suffix) = name.strip_prefix("start.") {
1571 suffixed_start_captures.insert(ix as u32, suffix.to_owned().into());
1572 }
1573 }
1574
1575 if let Some(indent_capture_ix) = indent_capture_ix {
1576 grammar.indents_config = Some(IndentConfig {
1577 query,
1578 indent_capture_ix,
1579 start_capture_ix,
1580 end_capture_ix,
1581 outdent_capture_ix,
1582 suffixed_start_captures,
1583 });
1584 }
1585 Ok(self)
1586 }
1587
1588 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1589 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1590 let query = Query::new(&grammar.ts_language, source)?;
1591 let mut language_capture_ix = None;
1592 let mut injection_language_capture_ix = None;
1593 let mut content_capture_ix = None;
1594 let mut injection_content_capture_ix = None;
1595 get_capture_indices(
1596 &query,
1597 &mut [
1598 ("language", &mut language_capture_ix),
1599 ("injection.language", &mut injection_language_capture_ix),
1600 ("content", &mut content_capture_ix),
1601 ("injection.content", &mut injection_content_capture_ix),
1602 ],
1603 );
1604 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1605 (None, Some(ix)) => Some(ix),
1606 (Some(_), Some(_)) => {
1607 anyhow::bail!("both language and injection.language captures are present");
1608 }
1609 _ => language_capture_ix,
1610 };
1611 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1612 (None, Some(ix)) => Some(ix),
1613 (Some(_), Some(_)) => {
1614 anyhow::bail!("both content and injection.content captures are present")
1615 }
1616 _ => content_capture_ix,
1617 };
1618 let patterns = (0..query.pattern_count())
1619 .map(|ix| {
1620 let mut config = InjectionPatternConfig::default();
1621 for setting in query.property_settings(ix) {
1622 match setting.key.as_ref() {
1623 "language" | "injection.language" => {
1624 config.language.clone_from(&setting.value);
1625 }
1626 "combined" | "injection.combined" => {
1627 config.combined = true;
1628 }
1629 _ => {}
1630 }
1631 }
1632 config
1633 })
1634 .collect();
1635 if let Some(content_capture_ix) = content_capture_ix {
1636 grammar.injection_config = Some(InjectionConfig {
1637 query,
1638 language_capture_ix,
1639 content_capture_ix,
1640 patterns,
1641 });
1642 }
1643 Ok(self)
1644 }
1645
1646 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1647 let query = {
1648 let grammar = self.grammar.as_ref().context("no grammar for language")?;
1649 Query::new(&grammar.ts_language, source)?
1650 };
1651
1652 let mut override_configs_by_id = HashMap::default();
1653 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1654 let mut range_is_inclusive = false;
1655 if name.starts_with('_') {
1656 continue;
1657 }
1658 if let Some(prefix) = name.strip_suffix(".inclusive") {
1659 name = prefix;
1660 range_is_inclusive = true;
1661 }
1662
1663 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1664 for server_name in &value.opt_into_language_servers {
1665 if !self
1666 .config
1667 .scope_opt_in_language_servers
1668 .contains(server_name)
1669 {
1670 util::debug_panic!(
1671 "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1672 );
1673 }
1674 }
1675
1676 override_configs_by_id.insert(
1677 ix as u32,
1678 OverrideEntry {
1679 name: name.to_string(),
1680 range_is_inclusive,
1681 value,
1682 },
1683 );
1684 }
1685
1686 let referenced_override_names = self.config.overrides.keys().chain(
1687 self.config
1688 .brackets
1689 .disabled_scopes_by_bracket_ix
1690 .iter()
1691 .flatten(),
1692 );
1693
1694 for referenced_name in referenced_override_names {
1695 if !override_configs_by_id
1696 .values()
1697 .any(|entry| entry.name == *referenced_name)
1698 {
1699 anyhow::bail!(
1700 "language {:?} has overrides in config not in query: {referenced_name:?}",
1701 self.config.name
1702 );
1703 }
1704 }
1705
1706 for entry in override_configs_by_id.values_mut() {
1707 entry.value.disabled_bracket_ixs = self
1708 .config
1709 .brackets
1710 .disabled_scopes_by_bracket_ix
1711 .iter()
1712 .enumerate()
1713 .filter_map(|(ix, disabled_scope_names)| {
1714 if disabled_scope_names.contains(&entry.name) {
1715 Some(ix as u16)
1716 } else {
1717 None
1718 }
1719 })
1720 .collect();
1721 }
1722
1723 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1724
1725 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1726 grammar.override_config = Some(OverrideConfig {
1727 query,
1728 values: override_configs_by_id,
1729 });
1730 Ok(self)
1731 }
1732
1733 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1734 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1735
1736 let query = Query::new(&grammar.ts_language, source)?;
1737 let mut redaction_capture_ix = None;
1738 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1739
1740 if let Some(redaction_capture_ix) = redaction_capture_ix {
1741 grammar.redactions_config = Some(RedactionConfig {
1742 query,
1743 redaction_capture_ix,
1744 });
1745 }
1746
1747 Ok(self)
1748 }
1749
1750 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1751 Arc::get_mut(self.grammar.as_mut()?)
1752 }
1753
1754 pub fn name(&self) -> LanguageName {
1755 self.config.name.clone()
1756 }
1757 pub fn manifest(&self) -> Option<&ManifestName> {
1758 self.manifest_name.as_ref()
1759 }
1760
1761 pub fn code_fence_block_name(&self) -> Arc<str> {
1762 self.config
1763 .code_fence_block_name
1764 .clone()
1765 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1766 }
1767
1768 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1769 self.context_provider.clone()
1770 }
1771
1772 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1773 self.toolchain.clone()
1774 }
1775
1776 pub fn highlight_text<'a>(
1777 self: &'a Arc<Self>,
1778 text: &'a Rope,
1779 range: Range<usize>,
1780 ) -> Vec<(Range<usize>, HighlightId)> {
1781 let mut result = Vec::new();
1782 if let Some(grammar) = &self.grammar {
1783 let tree = grammar.parse_text(text, None);
1784 let captures =
1785 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1786 grammar.highlights_query.as_ref()
1787 });
1788 let highlight_maps = vec![grammar.highlight_map()];
1789 let mut offset = 0;
1790 for chunk in
1791 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1792 {
1793 let end_offset = offset + chunk.text.len();
1794 if let Some(highlight_id) = chunk.syntax_highlight_id
1795 && !highlight_id.is_default()
1796 {
1797 result.push((offset..end_offset, highlight_id));
1798 }
1799 offset = end_offset;
1800 }
1801 }
1802 result
1803 }
1804
1805 pub fn path_suffixes(&self) -> &[String] {
1806 &self.config.matcher.path_suffixes
1807 }
1808
1809 pub fn should_autoclose_before(&self, c: char) -> bool {
1810 c.is_whitespace() || self.config.autoclose_before.contains(c)
1811 }
1812
1813 pub fn set_theme(&self, theme: &SyntaxTheme) {
1814 if let Some(grammar) = self.grammar.as_ref()
1815 && let Some(highlights_query) = &grammar.highlights_query
1816 {
1817 *grammar.highlight_map.lock() =
1818 HighlightMap::new(highlights_query.capture_names(), theme);
1819 }
1820 }
1821
1822 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1823 self.grammar.as_ref()
1824 }
1825
1826 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1827 LanguageScope {
1828 language: self.clone(),
1829 override_id: None,
1830 }
1831 }
1832
1833 pub fn lsp_id(&self) -> String {
1834 self.config.name.lsp_id()
1835 }
1836
1837 pub fn prettier_parser_name(&self) -> Option<&str> {
1838 self.config.prettier_parser_name.as_deref()
1839 }
1840
1841 pub fn config(&self) -> &LanguageConfig {
1842 &self.config
1843 }
1844}
1845
1846impl LanguageScope {
1847 pub fn path_suffixes(&self) -> &[String] {
1848 self.language.path_suffixes()
1849 }
1850
1851 pub fn language_name(&self) -> LanguageName {
1852 self.language.config.name.clone()
1853 }
1854
1855 pub fn collapsed_placeholder(&self) -> &str {
1856 self.language.config.collapsed_placeholder.as_ref()
1857 }
1858
1859 /// Returns line prefix that is inserted in e.g. line continuations or
1860 /// in `toggle comments` action.
1861 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1862 Override::as_option(
1863 self.config_override().map(|o| &o.line_comments),
1864 Some(&self.language.config.line_comments),
1865 )
1866 .map_or([].as_slice(), |e| e.as_slice())
1867 }
1868
1869 /// Config for block comments for this language.
1870 pub fn block_comment(&self) -> Option<&BlockCommentConfig> {
1871 Override::as_option(
1872 self.config_override().map(|o| &o.block_comment),
1873 self.language.config.block_comment.as_ref(),
1874 )
1875 }
1876
1877 /// Config for documentation-style block comments for this language.
1878 pub fn documentation_comment(&self) -> Option<&BlockCommentConfig> {
1879 self.language.config.documentation_comment.as_ref()
1880 }
1881
1882 /// Returns additional regex patterns that act as prefix markers for creating
1883 /// boundaries during rewrapping.
1884 ///
1885 /// By default, Zed treats as paragraph and comment prefixes as boundaries.
1886 pub fn rewrap_prefixes(&self) -> &[Regex] {
1887 &self.language.config.rewrap_prefixes
1888 }
1889
1890 /// Returns a list of language-specific word characters.
1891 ///
1892 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1893 /// the purpose of actions like 'move to next word end` or whole-word search.
1894 /// It additionally accounts for language's additional word characters.
1895 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1896 Override::as_option(
1897 self.config_override().map(|o| &o.word_characters),
1898 Some(&self.language.config.word_characters),
1899 )
1900 }
1901
1902 /// Returns a list of language-specific characters that are considered part of
1903 /// a completion query.
1904 pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1905 Override::as_option(
1906 self.config_override()
1907 .map(|o| &o.completion_query_characters),
1908 Some(&self.language.config.completion_query_characters),
1909 )
1910 }
1911
1912 /// Returns whether to prefer snippet `label` over `new_text` to replace text when
1913 /// completion is accepted.
1914 ///
1915 /// In cases like when cursor is in string or renaming existing function,
1916 /// you don't want to expand function signature instead just want function name
1917 /// to replace existing one.
1918 pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
1919 self.config_override()
1920 .and_then(|o| o.prefer_label_for_snippet)
1921 .unwrap_or(false)
1922 }
1923
1924 /// Returns a list of bracket pairs for a given language with an additional
1925 /// piece of information about whether the particular bracket pair is currently active for a given language.
1926 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1927 let mut disabled_ids = self
1928 .config_override()
1929 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1930 self.language
1931 .config
1932 .brackets
1933 .pairs
1934 .iter()
1935 .enumerate()
1936 .map(move |(ix, bracket)| {
1937 let mut is_enabled = true;
1938 if let Some(next_disabled_ix) = disabled_ids.first()
1939 && ix == *next_disabled_ix as usize
1940 {
1941 disabled_ids = &disabled_ids[1..];
1942 is_enabled = false;
1943 }
1944 (bracket, is_enabled)
1945 })
1946 }
1947
1948 pub fn should_autoclose_before(&self, c: char) -> bool {
1949 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1950 }
1951
1952 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1953 let config = &self.language.config;
1954 let opt_in_servers = &config.scope_opt_in_language_servers;
1955 if opt_in_servers.contains(name) {
1956 if let Some(over) = self.config_override() {
1957 over.opt_into_language_servers.contains(name)
1958 } else {
1959 false
1960 }
1961 } else {
1962 true
1963 }
1964 }
1965
1966 pub fn override_name(&self) -> Option<&str> {
1967 let id = self.override_id?;
1968 let grammar = self.language.grammar.as_ref()?;
1969 let override_config = grammar.override_config.as_ref()?;
1970 override_config.values.get(&id).map(|e| e.name.as_str())
1971 }
1972
1973 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1974 let id = self.override_id?;
1975 let grammar = self.language.grammar.as_ref()?;
1976 let override_config = grammar.override_config.as_ref()?;
1977 override_config.values.get(&id).map(|e| &e.value)
1978 }
1979}
1980
1981impl Hash for Language {
1982 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1983 self.id.hash(state)
1984 }
1985}
1986
1987impl PartialEq for Language {
1988 fn eq(&self, other: &Self) -> bool {
1989 self.id.eq(&other.id)
1990 }
1991}
1992
1993impl Eq for Language {}
1994
1995impl Debug for Language {
1996 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1997 f.debug_struct("Language")
1998 .field("name", &self.config.name)
1999 .finish()
2000 }
2001}
2002
2003impl Grammar {
2004 pub fn id(&self) -> GrammarId {
2005 self.id
2006 }
2007
2008 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
2009 with_parser(|parser| {
2010 parser
2011 .set_language(&self.ts_language)
2012 .expect("incompatible grammar");
2013 let mut chunks = text.chunks_in_range(0..text.len());
2014 parser
2015 .parse_with_options(
2016 &mut move |offset, _| {
2017 chunks.seek(offset);
2018 chunks.next().unwrap_or("").as_bytes()
2019 },
2020 old_tree.as_ref(),
2021 None,
2022 )
2023 .unwrap()
2024 })
2025 }
2026
2027 pub fn highlight_map(&self) -> HighlightMap {
2028 self.highlight_map.lock().clone()
2029 }
2030
2031 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
2032 let capture_id = self
2033 .highlights_query
2034 .as_ref()?
2035 .capture_index_for_name(name)?;
2036 Some(self.highlight_map.lock().get(capture_id))
2037 }
2038
2039 pub fn debug_variables_config(&self) -> Option<&DebugVariablesConfig> {
2040 self.debug_variables_config.as_ref()
2041 }
2042}
2043
2044impl CodeLabel {
2045 pub fn fallback_for_completion(
2046 item: &lsp::CompletionItem,
2047 language: Option<&Language>,
2048 ) -> Self {
2049 let highlight_id = item.kind.and_then(|kind| {
2050 let grammar = language?.grammar()?;
2051 use lsp::CompletionItemKind as Kind;
2052 match kind {
2053 Kind::CLASS => grammar.highlight_id_for_name("type"),
2054 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
2055 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
2056 Kind::ENUM => grammar
2057 .highlight_id_for_name("enum")
2058 .or_else(|| grammar.highlight_id_for_name("type")),
2059 Kind::ENUM_MEMBER => grammar
2060 .highlight_id_for_name("variant")
2061 .or_else(|| grammar.highlight_id_for_name("property")),
2062 Kind::FIELD => grammar.highlight_id_for_name("property"),
2063 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
2064 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
2065 Kind::METHOD => grammar
2066 .highlight_id_for_name("function.method")
2067 .or_else(|| grammar.highlight_id_for_name("function")),
2068 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
2069 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
2070 Kind::STRUCT => grammar.highlight_id_for_name("type"),
2071 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
2072 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
2073 _ => None,
2074 }
2075 });
2076
2077 let label = &item.label;
2078 let label_length = label.len();
2079 let runs = highlight_id
2080 .map(|highlight_id| vec![(0..label_length, highlight_id)])
2081 .unwrap_or_default();
2082 let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
2083 format!("{label} {detail}")
2084 } else if let Some(description) = item
2085 .label_details
2086 .as_ref()
2087 .and_then(|label_details| label_details.description.as_deref())
2088 .filter(|description| description != label)
2089 {
2090 format!("{label} {description}")
2091 } else {
2092 label.clone()
2093 };
2094 let filter_range = item
2095 .filter_text
2096 .as_deref()
2097 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2098 .unwrap_or(0..label_length);
2099 Self {
2100 text,
2101 runs,
2102 filter_range,
2103 }
2104 }
2105
2106 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
2107 let filter_range = filter_text
2108 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2109 .unwrap_or(0..text.len());
2110 Self {
2111 runs: Vec::new(),
2112 filter_range,
2113 text,
2114 }
2115 }
2116
2117 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2118 let start_ix = self.text.len();
2119 self.text.push_str(text);
2120 let end_ix = self.text.len();
2121 if let Some(highlight) = highlight {
2122 self.runs.push((start_ix..end_ix, highlight));
2123 }
2124 }
2125
2126 pub fn text(&self) -> &str {
2127 self.text.as_str()
2128 }
2129
2130 pub fn filter_text(&self) -> &str {
2131 &self.text[self.filter_range.clone()]
2132 }
2133}
2134
2135impl From<String> for CodeLabel {
2136 fn from(value: String) -> Self {
2137 Self::plain(value, None)
2138 }
2139}
2140
2141impl From<&str> for CodeLabel {
2142 fn from(value: &str) -> Self {
2143 Self::plain(value.to_string(), None)
2144 }
2145}
2146
2147impl Ord for LanguageMatcher {
2148 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2149 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2150 self.first_line_pattern
2151 .as_ref()
2152 .map(Regex::as_str)
2153 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2154 })
2155 }
2156}
2157
2158impl PartialOrd for LanguageMatcher {
2159 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2160 Some(self.cmp(other))
2161 }
2162}
2163
2164impl Eq for LanguageMatcher {}
2165
2166impl PartialEq for LanguageMatcher {
2167 fn eq(&self, other: &Self) -> bool {
2168 self.path_suffixes == other.path_suffixes
2169 && self.first_line_pattern.as_ref().map(Regex::as_str)
2170 == other.first_line_pattern.as_ref().map(Regex::as_str)
2171 }
2172}
2173
2174#[cfg(any(test, feature = "test-support"))]
2175impl Default for FakeLspAdapter {
2176 fn default() -> Self {
2177 Self {
2178 name: "the-fake-language-server",
2179 capabilities: lsp::LanguageServer::full_capabilities(),
2180 initializer: None,
2181 disk_based_diagnostics_progress_token: None,
2182 initialization_options: None,
2183 disk_based_diagnostics_sources: Vec::new(),
2184 prettier_plugins: Vec::new(),
2185 language_server_binary: LanguageServerBinary {
2186 path: "/the/fake/lsp/path".into(),
2187 arguments: vec![],
2188 env: Default::default(),
2189 },
2190 label_for_completion: None,
2191 }
2192 }
2193}
2194
2195#[cfg(any(test, feature = "test-support"))]
2196#[async_trait(?Send)]
2197impl LspAdapter for FakeLspAdapter {
2198 fn name(&self) -> LanguageServerName {
2199 LanguageServerName(self.name.into())
2200 }
2201
2202 async fn check_if_user_installed(
2203 &self,
2204 _: &dyn LspAdapterDelegate,
2205 _: Option<Toolchain>,
2206 _: &AsyncApp,
2207 ) -> Option<LanguageServerBinary> {
2208 Some(self.language_server_binary.clone())
2209 }
2210
2211 fn get_language_server_command<'a>(
2212 self: Arc<Self>,
2213 _: Arc<dyn LspAdapterDelegate>,
2214 _: Option<Toolchain>,
2215 _: LanguageServerBinaryOptions,
2216 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2217 _: &'a mut AsyncApp,
2218 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2219 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2220 }
2221
2222 async fn fetch_latest_server_version(
2223 &self,
2224 _: &dyn LspAdapterDelegate,
2225 ) -> Result<Box<dyn 'static + Send + Any>> {
2226 unreachable!();
2227 }
2228
2229 async fn fetch_server_binary(
2230 &self,
2231 _: Box<dyn 'static + Send + Any>,
2232 _: PathBuf,
2233 _: &dyn LspAdapterDelegate,
2234 ) -> Result<LanguageServerBinary> {
2235 unreachable!();
2236 }
2237
2238 async fn cached_server_binary(
2239 &self,
2240 _: PathBuf,
2241 _: &dyn LspAdapterDelegate,
2242 ) -> Option<LanguageServerBinary> {
2243 unreachable!();
2244 }
2245
2246 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2247 self.disk_based_diagnostics_sources.clone()
2248 }
2249
2250 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2251 self.disk_based_diagnostics_progress_token.clone()
2252 }
2253
2254 async fn initialization_options(
2255 self: Arc<Self>,
2256 _: &dyn Fs,
2257 _: &Arc<dyn LspAdapterDelegate>,
2258 ) -> Result<Option<Value>> {
2259 Ok(self.initialization_options.clone())
2260 }
2261
2262 async fn label_for_completion(
2263 &self,
2264 item: &lsp::CompletionItem,
2265 language: &Arc<Language>,
2266 ) -> Option<CodeLabel> {
2267 let label_for_completion = self.label_for_completion.as_ref()?;
2268 label_for_completion(item, language)
2269 }
2270}
2271
2272fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2273 for (ix, name) in query.capture_names().iter().enumerate() {
2274 for (capture_name, index) in captures.iter_mut() {
2275 if capture_name == name {
2276 **index = Some(ix as u32);
2277 break;
2278 }
2279 }
2280 }
2281}
2282
2283pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2284 lsp::Position::new(point.row, point.column)
2285}
2286
2287pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2288 Unclipped(PointUtf16::new(point.line, point.character))
2289}
2290
2291pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2292 anyhow::ensure!(
2293 range.start <= range.end,
2294 "Inverted range provided to an LSP request: {:?}-{:?}",
2295 range.start,
2296 range.end
2297 );
2298 Ok(lsp::Range {
2299 start: point_to_lsp(range.start),
2300 end: point_to_lsp(range.end),
2301 })
2302}
2303
2304pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2305 let mut start = point_from_lsp(range.start);
2306 let mut end = point_from_lsp(range.end);
2307 if start > end {
2308 log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2309 mem::swap(&mut start, &mut end);
2310 }
2311 start..end
2312}
2313
2314#[cfg(test)]
2315mod tests {
2316 use super::*;
2317 use gpui::TestAppContext;
2318 use pretty_assertions::assert_matches;
2319
2320 #[gpui::test(iterations = 10)]
2321 async fn test_language_loading(cx: &mut TestAppContext) {
2322 let languages = LanguageRegistry::test(cx.executor());
2323 let languages = Arc::new(languages);
2324 languages.register_native_grammars([
2325 ("json", tree_sitter_json::LANGUAGE),
2326 ("rust", tree_sitter_rust::LANGUAGE),
2327 ]);
2328 languages.register_test_language(LanguageConfig {
2329 name: "JSON".into(),
2330 grammar: Some("json".into()),
2331 matcher: LanguageMatcher {
2332 path_suffixes: vec!["json".into()],
2333 ..Default::default()
2334 },
2335 ..Default::default()
2336 });
2337 languages.register_test_language(LanguageConfig {
2338 name: "Rust".into(),
2339 grammar: Some("rust".into()),
2340 matcher: LanguageMatcher {
2341 path_suffixes: vec!["rs".into()],
2342 ..Default::default()
2343 },
2344 ..Default::default()
2345 });
2346 assert_eq!(
2347 languages.language_names(),
2348 &[
2349 LanguageName::new("JSON"),
2350 LanguageName::new("Plain Text"),
2351 LanguageName::new("Rust"),
2352 ]
2353 );
2354
2355 let rust1 = languages.language_for_name("Rust");
2356 let rust2 = languages.language_for_name("Rust");
2357
2358 // Ensure language is still listed even if it's being loaded.
2359 assert_eq!(
2360 languages.language_names(),
2361 &[
2362 LanguageName::new("JSON"),
2363 LanguageName::new("Plain Text"),
2364 LanguageName::new("Rust"),
2365 ]
2366 );
2367
2368 let (rust1, rust2) = futures::join!(rust1, rust2);
2369 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2370
2371 // Ensure language is still listed even after loading it.
2372 assert_eq!(
2373 languages.language_names(),
2374 &[
2375 LanguageName::new("JSON"),
2376 LanguageName::new("Plain Text"),
2377 LanguageName::new("Rust"),
2378 ]
2379 );
2380
2381 // Loading an unknown language returns an error.
2382 assert!(languages.language_for_name("Unknown").await.is_err());
2383 }
2384
2385 #[gpui::test]
2386 async fn test_completion_label_omits_duplicate_data() {
2387 let regular_completion_item_1 = lsp::CompletionItem {
2388 label: "regular1".to_string(),
2389 detail: Some("detail1".to_string()),
2390 label_details: Some(lsp::CompletionItemLabelDetails {
2391 detail: None,
2392 description: Some("description 1".to_string()),
2393 }),
2394 ..lsp::CompletionItem::default()
2395 };
2396
2397 let regular_completion_item_2 = lsp::CompletionItem {
2398 label: "regular2".to_string(),
2399 label_details: Some(lsp::CompletionItemLabelDetails {
2400 detail: None,
2401 description: Some("description 2".to_string()),
2402 }),
2403 ..lsp::CompletionItem::default()
2404 };
2405
2406 let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2407 detail: Some(regular_completion_item_1.label.clone()),
2408 ..regular_completion_item_1.clone()
2409 };
2410
2411 let completion_item_with_duplicate_detail = lsp::CompletionItem {
2412 detail: Some(regular_completion_item_1.label.clone()),
2413 label_details: None,
2414 ..regular_completion_item_1.clone()
2415 };
2416
2417 let completion_item_with_duplicate_description = lsp::CompletionItem {
2418 label_details: Some(lsp::CompletionItemLabelDetails {
2419 detail: None,
2420 description: Some(regular_completion_item_2.label.clone()),
2421 }),
2422 ..regular_completion_item_2.clone()
2423 };
2424
2425 assert_eq!(
2426 CodeLabel::fallback_for_completion(®ular_completion_item_1, None).text,
2427 format!(
2428 "{} {}",
2429 regular_completion_item_1.label,
2430 regular_completion_item_1.detail.unwrap()
2431 ),
2432 "LSP completion items with both detail and label_details.description should prefer detail"
2433 );
2434 assert_eq!(
2435 CodeLabel::fallback_for_completion(®ular_completion_item_2, None).text,
2436 format!(
2437 "{} {}",
2438 regular_completion_item_2.label,
2439 regular_completion_item_2
2440 .label_details
2441 .as_ref()
2442 .unwrap()
2443 .description
2444 .as_ref()
2445 .unwrap()
2446 ),
2447 "LSP completion items without detail but with label_details.description should use that"
2448 );
2449 assert_eq!(
2450 CodeLabel::fallback_for_completion(
2451 &completion_item_with_duplicate_detail_and_proper_description,
2452 None
2453 )
2454 .text,
2455 format!(
2456 "{} {}",
2457 regular_completion_item_1.label,
2458 regular_completion_item_1
2459 .label_details
2460 .as_ref()
2461 .unwrap()
2462 .description
2463 .as_ref()
2464 .unwrap()
2465 ),
2466 "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2467 );
2468 assert_eq!(
2469 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2470 regular_completion_item_1.label,
2471 "LSP completion items with duplicate label and detail, should omit the detail"
2472 );
2473 assert_eq!(
2474 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2475 .text,
2476 regular_completion_item_2.label,
2477 "LSP completion items with duplicate label and detail, should omit the detail"
2478 );
2479 }
2480
2481 #[test]
2482 fn test_deserializing_comments_backwards_compat() {
2483 // current version of `block_comment` and `documentation_comment` work
2484 {
2485 let config: LanguageConfig = ::toml::from_str(
2486 r#"
2487 name = "Foo"
2488 block_comment = { start = "a", end = "b", prefix = "c", tab_size = 1 }
2489 documentation_comment = { start = "d", end = "e", prefix = "f", tab_size = 2 }
2490 "#,
2491 )
2492 .unwrap();
2493 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2494 assert_matches!(
2495 config.documentation_comment,
2496 Some(BlockCommentConfig { .. })
2497 );
2498
2499 let block_config = config.block_comment.unwrap();
2500 assert_eq!(block_config.start.as_ref(), "a");
2501 assert_eq!(block_config.end.as_ref(), "b");
2502 assert_eq!(block_config.prefix.as_ref(), "c");
2503 assert_eq!(block_config.tab_size, 1);
2504
2505 let doc_config = config.documentation_comment.unwrap();
2506 assert_eq!(doc_config.start.as_ref(), "d");
2507 assert_eq!(doc_config.end.as_ref(), "e");
2508 assert_eq!(doc_config.prefix.as_ref(), "f");
2509 assert_eq!(doc_config.tab_size, 2);
2510 }
2511
2512 // former `documentation` setting is read into `documentation_comment`
2513 {
2514 let config: LanguageConfig = ::toml::from_str(
2515 r#"
2516 name = "Foo"
2517 documentation = { start = "a", end = "b", prefix = "c", tab_size = 1}
2518 "#,
2519 )
2520 .unwrap();
2521 assert_matches!(
2522 config.documentation_comment,
2523 Some(BlockCommentConfig { .. })
2524 );
2525
2526 let config = config.documentation_comment.unwrap();
2527 assert_eq!(config.start.as_ref(), "a");
2528 assert_eq!(config.end.as_ref(), "b");
2529 assert_eq!(config.prefix.as_ref(), "c");
2530 assert_eq!(config.tab_size, 1);
2531 }
2532
2533 // old block_comment format is read into BlockCommentConfig
2534 {
2535 let config: LanguageConfig = ::toml::from_str(
2536 r#"
2537 name = "Foo"
2538 block_comment = ["a", "b"]
2539 "#,
2540 )
2541 .unwrap();
2542 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2543
2544 let config = config.block_comment.unwrap();
2545 assert_eq!(config.start.as_ref(), "a");
2546 assert_eq!(config.end.as_ref(), "b");
2547 assert_eq!(config.prefix.as_ref(), "");
2548 assert_eq!(config.tab_size, 0);
2549 }
2550 }
2551}