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 /// The name of a Prettier parser that will be used for this language when no file path is available.
724 /// If there's a parser name in the language settings, that will be used instead.
725 #[serde(default)]
726 pub prettier_parser_name: Option<String>,
727 /// If true, this language is only for syntax highlighting via an injection into other
728 /// languages, but should not appear to the user as a distinct language.
729 #[serde(default)]
730 pub hidden: bool,
731 /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
732 #[serde(default)]
733 pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
734 /// A list of characters that Zed should treat as word characters for completion queries.
735 #[serde(default)]
736 pub completion_query_characters: HashSet<char>,
737 /// A list of preferred debuggers for this language.
738 #[serde(default)]
739 pub debuggers: IndexSet<SharedString>,
740}
741
742#[derive(Clone, Debug, Deserialize, Default, JsonSchema)]
743pub struct DecreaseIndentConfig {
744 #[serde(default, deserialize_with = "deserialize_regex")]
745 #[schemars(schema_with = "regex_json_schema")]
746 pub pattern: Option<Regex>,
747 #[serde(default)]
748 pub valid_after: Vec<String>,
749}
750
751#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
752pub struct LanguageMatcher {
753 /// 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`.
754 #[serde(default)]
755 pub path_suffixes: Vec<String>,
756 /// A regex pattern that determines whether the language should be assigned to a file or not.
757 #[serde(
758 default,
759 serialize_with = "serialize_regex",
760 deserialize_with = "deserialize_regex"
761 )]
762 #[schemars(schema_with = "regex_json_schema")]
763 pub first_line_pattern: Option<Regex>,
764}
765
766/// The configuration for JSX tag auto-closing.
767#[derive(Clone, Deserialize, JsonSchema)]
768pub struct JsxTagAutoCloseConfig {
769 /// The name of the node for a opening tag
770 pub open_tag_node_name: String,
771 /// The name of the node for an closing tag
772 pub close_tag_node_name: String,
773 /// The name of the node for a complete element with children for open and close tags
774 pub jsx_element_node_name: String,
775 /// The name of the node found within both opening and closing
776 /// tags that describes the tag name
777 pub tag_name_node_name: String,
778 /// Alternate Node names for tag names.
779 /// Specifically needed as TSX represents the name in `<Foo.Bar>`
780 /// as `member_expression` rather than `identifier` as usual
781 #[serde(default)]
782 pub tag_name_node_name_alternates: Vec<String>,
783 /// Some grammars are smart enough to detect a closing tag
784 /// that is not valid i.e. doesn't match it's corresponding
785 /// opening tag or does not have a corresponding opening tag
786 /// This should be set to the name of the node for invalid
787 /// closing tags if the grammar contains such a node, otherwise
788 /// detecting already closed tags will not work properly
789 #[serde(default)]
790 pub erroneous_close_tag_node_name: Option<String>,
791 /// See above for erroneous_close_tag_node_name for details
792 /// This should be set if the node used for the tag name
793 /// within erroneous closing tags is different from the
794 /// normal tag name node name
795 #[serde(default)]
796 pub erroneous_close_tag_name_node_name: Option<String>,
797}
798
799/// The configuration for block comments for this language.
800#[derive(Clone, Debug, JsonSchema, PartialEq)]
801pub struct BlockCommentConfig {
802 /// A start tag of block comment.
803 pub start: Arc<str>,
804 /// A end tag of block comment.
805 pub end: Arc<str>,
806 /// A character to add as a prefix when a new line is added to a block comment.
807 pub prefix: Arc<str>,
808 /// A indent to add for prefix and end line upon new line.
809 pub tab_size: u32,
810}
811
812impl<'de> Deserialize<'de> for BlockCommentConfig {
813 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
814 where
815 D: Deserializer<'de>,
816 {
817 #[derive(Deserialize)]
818 #[serde(untagged)]
819 enum BlockCommentConfigHelper {
820 New {
821 start: Arc<str>,
822 end: Arc<str>,
823 prefix: Arc<str>,
824 tab_size: u32,
825 },
826 Old([Arc<str>; 2]),
827 }
828
829 match BlockCommentConfigHelper::deserialize(deserializer)? {
830 BlockCommentConfigHelper::New {
831 start,
832 end,
833 prefix,
834 tab_size,
835 } => Ok(BlockCommentConfig {
836 start,
837 end,
838 prefix,
839 tab_size,
840 }),
841 BlockCommentConfigHelper::Old([start, end]) => Ok(BlockCommentConfig {
842 start,
843 end,
844 prefix: "".into(),
845 tab_size: 0,
846 }),
847 }
848 }
849}
850
851/// Represents a language for the given range. Some languages (e.g. HTML)
852/// interleave several languages together, thus a single buffer might actually contain
853/// several nested scopes.
854#[derive(Clone, Debug)]
855pub struct LanguageScope {
856 language: Arc<Language>,
857 override_id: Option<u32>,
858}
859
860#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
861pub struct LanguageConfigOverride {
862 #[serde(default)]
863 pub line_comments: Override<Vec<Arc<str>>>,
864 #[serde(default)]
865 pub block_comment: Override<BlockCommentConfig>,
866 #[serde(skip)]
867 pub disabled_bracket_ixs: Vec<u16>,
868 #[serde(default)]
869 pub word_characters: Override<HashSet<char>>,
870 #[serde(default)]
871 pub completion_query_characters: Override<HashSet<char>>,
872 #[serde(default)]
873 pub opt_into_language_servers: Vec<LanguageServerName>,
874 #[serde(default)]
875 pub prefer_label_for_snippet: Option<bool>,
876}
877
878#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
879#[serde(untagged)]
880pub enum Override<T> {
881 Remove { remove: bool },
882 Set(T),
883}
884
885impl<T> Default for Override<T> {
886 fn default() -> Self {
887 Override::Remove { remove: false }
888 }
889}
890
891impl<T> Override<T> {
892 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
893 match this {
894 Some(Self::Set(value)) => Some(value),
895 Some(Self::Remove { remove: true }) => None,
896 Some(Self::Remove { remove: false }) | None => original,
897 }
898 }
899}
900
901impl Default for LanguageConfig {
902 fn default() -> Self {
903 Self {
904 name: LanguageName::new(""),
905 code_fence_block_name: None,
906 grammar: None,
907 matcher: LanguageMatcher::default(),
908 brackets: Default::default(),
909 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
910 auto_indent_on_paste: None,
911 increase_indent_pattern: Default::default(),
912 decrease_indent_pattern: Default::default(),
913 decrease_indent_patterns: Default::default(),
914 autoclose_before: Default::default(),
915 line_comments: Default::default(),
916 block_comment: Default::default(),
917 documentation_comment: Default::default(),
918 rewrap_prefixes: Default::default(),
919 scope_opt_in_language_servers: Default::default(),
920 overrides: Default::default(),
921 word_characters: Default::default(),
922 collapsed_placeholder: Default::default(),
923 hard_tabs: None,
924 tab_size: None,
925 soft_wrap: None,
926 prettier_parser_name: None,
927 hidden: false,
928 jsx_tag_auto_close: None,
929 completion_query_characters: Default::default(),
930 debuggers: Default::default(),
931 }
932 }
933}
934
935fn auto_indent_using_last_non_empty_line_default() -> bool {
936 true
937}
938
939fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
940 let source = Option::<String>::deserialize(d)?;
941 if let Some(source) = source {
942 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
943 } else {
944 Ok(None)
945 }
946}
947
948fn regex_json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
949 json_schema!({
950 "type": "string"
951 })
952}
953
954fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
955where
956 S: Serializer,
957{
958 match regex {
959 Some(regex) => serializer.serialize_str(regex.as_str()),
960 None => serializer.serialize_none(),
961 }
962}
963
964fn deserialize_regex_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Regex>, D::Error> {
965 let sources = Vec::<String>::deserialize(d)?;
966 sources
967 .into_iter()
968 .map(|source| regex::Regex::new(&source))
969 .collect::<Result<_, _>>()
970 .map_err(de::Error::custom)
971}
972
973fn regex_vec_json_schema(_: &mut SchemaGenerator) -> schemars::Schema {
974 json_schema!({
975 "type": "array",
976 "items": { "type": "string" }
977 })
978}
979
980#[doc(hidden)]
981#[cfg(any(test, feature = "test-support"))]
982pub struct FakeLspAdapter {
983 pub name: &'static str,
984 pub initialization_options: Option<Value>,
985 pub prettier_plugins: Vec<&'static str>,
986 pub disk_based_diagnostics_progress_token: Option<String>,
987 pub disk_based_diagnostics_sources: Vec<String>,
988 pub language_server_binary: LanguageServerBinary,
989
990 pub capabilities: lsp::ServerCapabilities,
991 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
992 pub label_for_completion: Option<
993 Box<
994 dyn 'static
995 + Send
996 + Sync
997 + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
998 >,
999 >,
1000}
1001
1002/// Configuration of handling bracket pairs for a given language.
1003///
1004/// This struct includes settings for defining which pairs of characters are considered brackets and
1005/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
1006#[derive(Clone, Debug, Default, JsonSchema)]
1007#[schemars(with = "Vec::<BracketPairContent>")]
1008pub struct BracketPairConfig {
1009 /// A list of character pairs that should be treated as brackets in the context of a given language.
1010 pub pairs: Vec<BracketPair>,
1011 /// A list of tree-sitter scopes for which a given bracket should not be active.
1012 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
1013 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
1014}
1015
1016impl BracketPairConfig {
1017 pub fn is_closing_brace(&self, c: char) -> bool {
1018 self.pairs.iter().any(|pair| pair.end.starts_with(c))
1019 }
1020}
1021
1022#[derive(Deserialize, JsonSchema)]
1023pub struct BracketPairContent {
1024 #[serde(flatten)]
1025 pub bracket_pair: BracketPair,
1026 #[serde(default)]
1027 pub not_in: Vec<String>,
1028}
1029
1030impl<'de> Deserialize<'de> for BracketPairConfig {
1031 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1032 where
1033 D: Deserializer<'de>,
1034 {
1035 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
1036 let (brackets, disabled_scopes_by_bracket_ix) = result
1037 .into_iter()
1038 .map(|entry| (entry.bracket_pair, entry.not_in))
1039 .unzip();
1040
1041 Ok(BracketPairConfig {
1042 pairs: brackets,
1043 disabled_scopes_by_bracket_ix,
1044 })
1045 }
1046}
1047
1048/// Describes a single bracket pair and how an editor should react to e.g. inserting
1049/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
1050#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
1051pub struct BracketPair {
1052 /// Starting substring for a bracket.
1053 pub start: String,
1054 /// Ending substring for a bracket.
1055 pub end: String,
1056 /// True if `end` should be automatically inserted right after `start` characters.
1057 pub close: bool,
1058 /// True if selected text should be surrounded by `start` and `end` characters.
1059 #[serde(default = "default_true")]
1060 pub surround: bool,
1061 /// True if an extra newline should be inserted while the cursor is in the middle
1062 /// of that bracket pair.
1063 pub newline: bool,
1064}
1065
1066#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1067pub struct LanguageId(usize);
1068
1069impl LanguageId {
1070 pub(crate) fn new() -> Self {
1071 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
1072 }
1073}
1074
1075pub struct Language {
1076 pub(crate) id: LanguageId,
1077 pub(crate) config: LanguageConfig,
1078 pub(crate) grammar: Option<Arc<Grammar>>,
1079 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1080 pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1081 pub(crate) manifest_name: Option<ManifestName>,
1082}
1083
1084#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1085pub struct GrammarId(pub usize);
1086
1087impl GrammarId {
1088 pub(crate) fn new() -> Self {
1089 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1090 }
1091}
1092
1093pub struct Grammar {
1094 id: GrammarId,
1095 pub ts_language: tree_sitter::Language,
1096 pub(crate) error_query: Option<Query>,
1097 pub(crate) highlights_query: Option<Query>,
1098 pub(crate) brackets_config: Option<BracketsConfig>,
1099 pub(crate) redactions_config: Option<RedactionConfig>,
1100 pub(crate) runnable_config: Option<RunnableConfig>,
1101 pub(crate) indents_config: Option<IndentConfig>,
1102 pub outline_config: Option<OutlineConfig>,
1103 pub text_object_config: Option<TextObjectConfig>,
1104 pub embedding_config: Option<EmbeddingConfig>,
1105 pub(crate) injection_config: Option<InjectionConfig>,
1106 pub(crate) override_config: Option<OverrideConfig>,
1107 pub(crate) debug_variables_config: Option<DebugVariablesConfig>,
1108 pub(crate) highlight_map: Mutex<HighlightMap>,
1109}
1110
1111struct IndentConfig {
1112 query: Query,
1113 indent_capture_ix: u32,
1114 start_capture_ix: Option<u32>,
1115 end_capture_ix: Option<u32>,
1116 outdent_capture_ix: Option<u32>,
1117 suffixed_start_captures: HashMap<u32, SharedString>,
1118}
1119
1120pub struct OutlineConfig {
1121 pub query: Query,
1122 pub item_capture_ix: u32,
1123 pub name_capture_ix: u32,
1124 pub context_capture_ix: Option<u32>,
1125 pub extra_context_capture_ix: Option<u32>,
1126 pub open_capture_ix: Option<u32>,
1127 pub close_capture_ix: Option<u32>,
1128 pub annotation_capture_ix: Option<u32>,
1129}
1130
1131#[derive(Debug, Clone, Copy, PartialEq)]
1132pub enum DebuggerTextObject {
1133 Variable,
1134 Scope,
1135}
1136
1137impl DebuggerTextObject {
1138 pub fn from_capture_name(name: &str) -> Option<DebuggerTextObject> {
1139 match name {
1140 "debug-variable" => Some(DebuggerTextObject::Variable),
1141 "debug-scope" => Some(DebuggerTextObject::Scope),
1142 _ => None,
1143 }
1144 }
1145}
1146
1147#[derive(Debug, Clone, Copy, PartialEq)]
1148pub enum TextObject {
1149 InsideFunction,
1150 AroundFunction,
1151 InsideClass,
1152 AroundClass,
1153 InsideComment,
1154 AroundComment,
1155}
1156
1157impl TextObject {
1158 pub fn from_capture_name(name: &str) -> Option<TextObject> {
1159 match name {
1160 "function.inside" => Some(TextObject::InsideFunction),
1161 "function.around" => Some(TextObject::AroundFunction),
1162 "class.inside" => Some(TextObject::InsideClass),
1163 "class.around" => Some(TextObject::AroundClass),
1164 "comment.inside" => Some(TextObject::InsideComment),
1165 "comment.around" => Some(TextObject::AroundComment),
1166 _ => None,
1167 }
1168 }
1169
1170 pub fn around(&self) -> Option<Self> {
1171 match self {
1172 TextObject::InsideFunction => Some(TextObject::AroundFunction),
1173 TextObject::InsideClass => Some(TextObject::AroundClass),
1174 TextObject::InsideComment => Some(TextObject::AroundComment),
1175 _ => None,
1176 }
1177 }
1178}
1179
1180pub struct TextObjectConfig {
1181 pub query: Query,
1182 pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1183}
1184
1185#[derive(Debug)]
1186pub struct EmbeddingConfig {
1187 pub query: Query,
1188 pub item_capture_ix: u32,
1189 pub name_capture_ix: Option<u32>,
1190 pub context_capture_ix: Option<u32>,
1191 pub collapse_capture_ix: Option<u32>,
1192 pub keep_capture_ix: Option<u32>,
1193}
1194
1195struct InjectionConfig {
1196 query: Query,
1197 content_capture_ix: u32,
1198 language_capture_ix: Option<u32>,
1199 patterns: Vec<InjectionPatternConfig>,
1200}
1201
1202struct RedactionConfig {
1203 pub query: Query,
1204 pub redaction_capture_ix: u32,
1205}
1206
1207#[derive(Clone, Debug, PartialEq)]
1208enum RunnableCapture {
1209 Named(SharedString),
1210 Run,
1211}
1212
1213struct RunnableConfig {
1214 pub query: Query,
1215 /// A mapping from capture indice to capture kind
1216 pub extra_captures: Vec<RunnableCapture>,
1217}
1218
1219struct OverrideConfig {
1220 query: Query,
1221 values: HashMap<u32, OverrideEntry>,
1222}
1223
1224#[derive(Debug)]
1225struct OverrideEntry {
1226 name: String,
1227 range_is_inclusive: bool,
1228 value: LanguageConfigOverride,
1229}
1230
1231#[derive(Default, Clone)]
1232struct InjectionPatternConfig {
1233 language: Option<Box<str>>,
1234 combined: bool,
1235}
1236
1237struct BracketsConfig {
1238 query: Query,
1239 open_capture_ix: u32,
1240 close_capture_ix: u32,
1241 patterns: Vec<BracketsPatternConfig>,
1242}
1243
1244#[derive(Clone, Debug, Default)]
1245struct BracketsPatternConfig {
1246 newline_only: bool,
1247}
1248
1249pub struct DebugVariablesConfig {
1250 pub query: Query,
1251 pub objects_by_capture_ix: Vec<(u32, DebuggerTextObject)>,
1252}
1253
1254impl Language {
1255 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1256 Self::new_with_id(LanguageId::new(), config, ts_language)
1257 }
1258
1259 pub fn id(&self) -> LanguageId {
1260 self.id
1261 }
1262
1263 fn new_with_id(
1264 id: LanguageId,
1265 config: LanguageConfig,
1266 ts_language: Option<tree_sitter::Language>,
1267 ) -> Self {
1268 Self {
1269 id,
1270 config,
1271 grammar: ts_language.map(|ts_language| {
1272 Arc::new(Grammar {
1273 id: GrammarId::new(),
1274 highlights_query: None,
1275 brackets_config: None,
1276 outline_config: None,
1277 text_object_config: None,
1278 embedding_config: None,
1279 indents_config: None,
1280 injection_config: None,
1281 override_config: None,
1282 redactions_config: None,
1283 runnable_config: None,
1284 error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1285 debug_variables_config: None,
1286 ts_language,
1287 highlight_map: Default::default(),
1288 })
1289 }),
1290 context_provider: None,
1291 toolchain: None,
1292 manifest_name: None,
1293 }
1294 }
1295
1296 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1297 self.context_provider = provider;
1298 self
1299 }
1300
1301 pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1302 self.toolchain = provider;
1303 self
1304 }
1305
1306 pub fn with_manifest(mut self, name: Option<ManifestName>) -> Self {
1307 self.manifest_name = name;
1308 self
1309 }
1310 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1311 if let Some(query) = queries.highlights {
1312 self = self
1313 .with_highlights_query(query.as_ref())
1314 .context("Error loading highlights query")?;
1315 }
1316 if let Some(query) = queries.brackets {
1317 self = self
1318 .with_brackets_query(query.as_ref())
1319 .context("Error loading brackets query")?;
1320 }
1321 if let Some(query) = queries.indents {
1322 self = self
1323 .with_indents_query(query.as_ref())
1324 .context("Error loading indents query")?;
1325 }
1326 if let Some(query) = queries.outline {
1327 self = self
1328 .with_outline_query(query.as_ref())
1329 .context("Error loading outline query")?;
1330 }
1331 if let Some(query) = queries.embedding {
1332 self = self
1333 .with_embedding_query(query.as_ref())
1334 .context("Error loading embedding query")?;
1335 }
1336 if let Some(query) = queries.injections {
1337 self = self
1338 .with_injection_query(query.as_ref())
1339 .context("Error loading injection query")?;
1340 }
1341 if let Some(query) = queries.overrides {
1342 self = self
1343 .with_override_query(query.as_ref())
1344 .context("Error loading override query")?;
1345 }
1346 if let Some(query) = queries.redactions {
1347 self = self
1348 .with_redaction_query(query.as_ref())
1349 .context("Error loading redaction query")?;
1350 }
1351 if let Some(query) = queries.runnables {
1352 self = self
1353 .with_runnable_query(query.as_ref())
1354 .context("Error loading runnables query")?;
1355 }
1356 if let Some(query) = queries.text_objects {
1357 self = self
1358 .with_text_object_query(query.as_ref())
1359 .context("Error loading textobject query")?;
1360 }
1361 if let Some(query) = queries.debugger {
1362 self = self
1363 .with_debug_variables_query(query.as_ref())
1364 .context("Error loading debug variables query")?;
1365 }
1366 Ok(self)
1367 }
1368
1369 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1370 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1371 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1372 Ok(self)
1373 }
1374
1375 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1376 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1377
1378 let query = Query::new(&grammar.ts_language, source)?;
1379 let extra_captures: Vec<_> = query
1380 .capture_names()
1381 .iter()
1382 .map(|&name| match name {
1383 "run" => RunnableCapture::Run,
1384 name => RunnableCapture::Named(name.to_string().into()),
1385 })
1386 .collect();
1387
1388 grammar.runnable_config = Some(RunnableConfig {
1389 extra_captures,
1390 query,
1391 });
1392
1393 Ok(self)
1394 }
1395
1396 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1397 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1398 let query = Query::new(&grammar.ts_language, source)?;
1399 let mut item_capture_ix = None;
1400 let mut name_capture_ix = None;
1401 let mut context_capture_ix = None;
1402 let mut extra_context_capture_ix = None;
1403 let mut open_capture_ix = None;
1404 let mut close_capture_ix = None;
1405 let mut annotation_capture_ix = None;
1406 get_capture_indices(
1407 &query,
1408 &mut [
1409 ("item", &mut item_capture_ix),
1410 ("name", &mut name_capture_ix),
1411 ("context", &mut context_capture_ix),
1412 ("context.extra", &mut extra_context_capture_ix),
1413 ("open", &mut open_capture_ix),
1414 ("close", &mut close_capture_ix),
1415 ("annotation", &mut annotation_capture_ix),
1416 ],
1417 );
1418 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1419 grammar.outline_config = Some(OutlineConfig {
1420 query,
1421 item_capture_ix,
1422 name_capture_ix,
1423 context_capture_ix,
1424 extra_context_capture_ix,
1425 open_capture_ix,
1426 close_capture_ix,
1427 annotation_capture_ix,
1428 });
1429 }
1430 Ok(self)
1431 }
1432
1433 pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1434 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1435 let query = Query::new(&grammar.ts_language, source)?;
1436
1437 let mut text_objects_by_capture_ix = Vec::new();
1438 for (ix, name) in query.capture_names().iter().enumerate() {
1439 if let Some(text_object) = TextObject::from_capture_name(name) {
1440 text_objects_by_capture_ix.push((ix as u32, text_object));
1441 }
1442 }
1443
1444 grammar.text_object_config = Some(TextObjectConfig {
1445 query,
1446 text_objects_by_capture_ix,
1447 });
1448 Ok(self)
1449 }
1450
1451 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1452 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1453 let query = Query::new(&grammar.ts_language, source)?;
1454 let mut item_capture_ix = None;
1455 let mut name_capture_ix = None;
1456 let mut context_capture_ix = None;
1457 let mut collapse_capture_ix = None;
1458 let mut keep_capture_ix = None;
1459 get_capture_indices(
1460 &query,
1461 &mut [
1462 ("item", &mut item_capture_ix),
1463 ("name", &mut name_capture_ix),
1464 ("context", &mut context_capture_ix),
1465 ("keep", &mut keep_capture_ix),
1466 ("collapse", &mut collapse_capture_ix),
1467 ],
1468 );
1469 if let Some(item_capture_ix) = item_capture_ix {
1470 grammar.embedding_config = Some(EmbeddingConfig {
1471 query,
1472 item_capture_ix,
1473 name_capture_ix,
1474 context_capture_ix,
1475 collapse_capture_ix,
1476 keep_capture_ix,
1477 });
1478 }
1479 Ok(self)
1480 }
1481
1482 pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1483 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1484 let query = Query::new(&grammar.ts_language, source)?;
1485
1486 let mut objects_by_capture_ix = Vec::new();
1487 for (ix, name) in query.capture_names().iter().enumerate() {
1488 if let Some(text_object) = DebuggerTextObject::from_capture_name(name) {
1489 objects_by_capture_ix.push((ix as u32, text_object));
1490 }
1491 }
1492
1493 grammar.debug_variables_config = Some(DebugVariablesConfig {
1494 query,
1495 objects_by_capture_ix,
1496 });
1497 Ok(self)
1498 }
1499
1500 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1501 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1502 let query = Query::new(&grammar.ts_language, source)?;
1503 let mut open_capture_ix = None;
1504 let mut close_capture_ix = None;
1505 get_capture_indices(
1506 &query,
1507 &mut [
1508 ("open", &mut open_capture_ix),
1509 ("close", &mut close_capture_ix),
1510 ],
1511 );
1512 let patterns = (0..query.pattern_count())
1513 .map(|ix| {
1514 let mut config = BracketsPatternConfig::default();
1515 for setting in query.property_settings(ix) {
1516 if setting.key.as_ref() == "newline.only" {
1517 config.newline_only = true
1518 }
1519 }
1520 config
1521 })
1522 .collect();
1523 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1524 grammar.brackets_config = Some(BracketsConfig {
1525 query,
1526 open_capture_ix,
1527 close_capture_ix,
1528 patterns,
1529 });
1530 }
1531 Ok(self)
1532 }
1533
1534 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1535 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1536 let query = Query::new(&grammar.ts_language, source)?;
1537 let mut indent_capture_ix = None;
1538 let mut start_capture_ix = None;
1539 let mut end_capture_ix = None;
1540 let mut outdent_capture_ix = None;
1541 get_capture_indices(
1542 &query,
1543 &mut [
1544 ("indent", &mut indent_capture_ix),
1545 ("start", &mut start_capture_ix),
1546 ("end", &mut end_capture_ix),
1547 ("outdent", &mut outdent_capture_ix),
1548 ],
1549 );
1550
1551 let mut suffixed_start_captures = HashMap::default();
1552 for (ix, name) in query.capture_names().iter().enumerate() {
1553 if let Some(suffix) = name.strip_prefix("start.") {
1554 suffixed_start_captures.insert(ix as u32, suffix.to_owned().into());
1555 }
1556 }
1557
1558 if let Some(indent_capture_ix) = indent_capture_ix {
1559 grammar.indents_config = Some(IndentConfig {
1560 query,
1561 indent_capture_ix,
1562 start_capture_ix,
1563 end_capture_ix,
1564 outdent_capture_ix,
1565 suffixed_start_captures,
1566 });
1567 }
1568 Ok(self)
1569 }
1570
1571 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1572 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1573 let query = Query::new(&grammar.ts_language, source)?;
1574 let mut language_capture_ix = None;
1575 let mut injection_language_capture_ix = None;
1576 let mut content_capture_ix = None;
1577 let mut injection_content_capture_ix = None;
1578 get_capture_indices(
1579 &query,
1580 &mut [
1581 ("language", &mut language_capture_ix),
1582 ("injection.language", &mut injection_language_capture_ix),
1583 ("content", &mut content_capture_ix),
1584 ("injection.content", &mut injection_content_capture_ix),
1585 ],
1586 );
1587 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1588 (None, Some(ix)) => Some(ix),
1589 (Some(_), Some(_)) => {
1590 anyhow::bail!("both language and injection.language captures are present");
1591 }
1592 _ => language_capture_ix,
1593 };
1594 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1595 (None, Some(ix)) => Some(ix),
1596 (Some(_), Some(_)) => {
1597 anyhow::bail!("both content and injection.content captures are present")
1598 }
1599 _ => content_capture_ix,
1600 };
1601 let patterns = (0..query.pattern_count())
1602 .map(|ix| {
1603 let mut config = InjectionPatternConfig::default();
1604 for setting in query.property_settings(ix) {
1605 match setting.key.as_ref() {
1606 "language" | "injection.language" => {
1607 config.language.clone_from(&setting.value);
1608 }
1609 "combined" | "injection.combined" => {
1610 config.combined = true;
1611 }
1612 _ => {}
1613 }
1614 }
1615 config
1616 })
1617 .collect();
1618 if let Some(content_capture_ix) = content_capture_ix {
1619 grammar.injection_config = Some(InjectionConfig {
1620 query,
1621 language_capture_ix,
1622 content_capture_ix,
1623 patterns,
1624 });
1625 }
1626 Ok(self)
1627 }
1628
1629 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1630 let query = {
1631 let grammar = self.grammar.as_ref().context("no grammar for language")?;
1632 Query::new(&grammar.ts_language, source)?
1633 };
1634
1635 let mut override_configs_by_id = HashMap::default();
1636 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1637 let mut range_is_inclusive = false;
1638 if name.starts_with('_') {
1639 continue;
1640 }
1641 if let Some(prefix) = name.strip_suffix(".inclusive") {
1642 name = prefix;
1643 range_is_inclusive = true;
1644 }
1645
1646 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1647 for server_name in &value.opt_into_language_servers {
1648 if !self
1649 .config
1650 .scope_opt_in_language_servers
1651 .contains(server_name)
1652 {
1653 util::debug_panic!(
1654 "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1655 );
1656 }
1657 }
1658
1659 override_configs_by_id.insert(
1660 ix as u32,
1661 OverrideEntry {
1662 name: name.to_string(),
1663 range_is_inclusive,
1664 value,
1665 },
1666 );
1667 }
1668
1669 let referenced_override_names = self.config.overrides.keys().chain(
1670 self.config
1671 .brackets
1672 .disabled_scopes_by_bracket_ix
1673 .iter()
1674 .flatten(),
1675 );
1676
1677 for referenced_name in referenced_override_names {
1678 if !override_configs_by_id
1679 .values()
1680 .any(|entry| entry.name == *referenced_name)
1681 {
1682 anyhow::bail!(
1683 "language {:?} has overrides in config not in query: {referenced_name:?}",
1684 self.config.name
1685 );
1686 }
1687 }
1688
1689 for entry in override_configs_by_id.values_mut() {
1690 entry.value.disabled_bracket_ixs = self
1691 .config
1692 .brackets
1693 .disabled_scopes_by_bracket_ix
1694 .iter()
1695 .enumerate()
1696 .filter_map(|(ix, disabled_scope_names)| {
1697 if disabled_scope_names.contains(&entry.name) {
1698 Some(ix as u16)
1699 } else {
1700 None
1701 }
1702 })
1703 .collect();
1704 }
1705
1706 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1707
1708 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1709 grammar.override_config = Some(OverrideConfig {
1710 query,
1711 values: override_configs_by_id,
1712 });
1713 Ok(self)
1714 }
1715
1716 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1717 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1718
1719 let query = Query::new(&grammar.ts_language, source)?;
1720 let mut redaction_capture_ix = None;
1721 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1722
1723 if let Some(redaction_capture_ix) = redaction_capture_ix {
1724 grammar.redactions_config = Some(RedactionConfig {
1725 query,
1726 redaction_capture_ix,
1727 });
1728 }
1729
1730 Ok(self)
1731 }
1732
1733 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1734 Arc::get_mut(self.grammar.as_mut()?)
1735 }
1736
1737 pub fn name(&self) -> LanguageName {
1738 self.config.name.clone()
1739 }
1740 pub fn manifest(&self) -> Option<&ManifestName> {
1741 self.manifest_name.as_ref()
1742 }
1743
1744 pub fn code_fence_block_name(&self) -> Arc<str> {
1745 self.config
1746 .code_fence_block_name
1747 .clone()
1748 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1749 }
1750
1751 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1752 self.context_provider.clone()
1753 }
1754
1755 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1756 self.toolchain.clone()
1757 }
1758
1759 pub fn highlight_text<'a>(
1760 self: &'a Arc<Self>,
1761 text: &'a Rope,
1762 range: Range<usize>,
1763 ) -> Vec<(Range<usize>, HighlightId)> {
1764 let mut result = Vec::new();
1765 if let Some(grammar) = &self.grammar {
1766 let tree = grammar.parse_text(text, None);
1767 let captures =
1768 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1769 grammar.highlights_query.as_ref()
1770 });
1771 let highlight_maps = vec![grammar.highlight_map()];
1772 let mut offset = 0;
1773 for chunk in
1774 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1775 {
1776 let end_offset = offset + chunk.text.len();
1777 if let Some(highlight_id) = chunk.syntax_highlight_id
1778 && !highlight_id.is_default()
1779 {
1780 result.push((offset..end_offset, highlight_id));
1781 }
1782 offset = end_offset;
1783 }
1784 }
1785 result
1786 }
1787
1788 pub fn path_suffixes(&self) -> &[String] {
1789 &self.config.matcher.path_suffixes
1790 }
1791
1792 pub fn should_autoclose_before(&self, c: char) -> bool {
1793 c.is_whitespace() || self.config.autoclose_before.contains(c)
1794 }
1795
1796 pub fn set_theme(&self, theme: &SyntaxTheme) {
1797 if let Some(grammar) = self.grammar.as_ref()
1798 && let Some(highlights_query) = &grammar.highlights_query
1799 {
1800 *grammar.highlight_map.lock() =
1801 HighlightMap::new(highlights_query.capture_names(), theme);
1802 }
1803 }
1804
1805 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1806 self.grammar.as_ref()
1807 }
1808
1809 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1810 LanguageScope {
1811 language: self.clone(),
1812 override_id: None,
1813 }
1814 }
1815
1816 pub fn lsp_id(&self) -> String {
1817 self.config.name.lsp_id()
1818 }
1819
1820 pub fn prettier_parser_name(&self) -> Option<&str> {
1821 self.config.prettier_parser_name.as_deref()
1822 }
1823
1824 pub fn config(&self) -> &LanguageConfig {
1825 &self.config
1826 }
1827}
1828
1829impl LanguageScope {
1830 pub fn path_suffixes(&self) -> &[String] {
1831 self.language.path_suffixes()
1832 }
1833
1834 pub fn language_name(&self) -> LanguageName {
1835 self.language.config.name.clone()
1836 }
1837
1838 pub fn collapsed_placeholder(&self) -> &str {
1839 self.language.config.collapsed_placeholder.as_ref()
1840 }
1841
1842 /// Returns line prefix that is inserted in e.g. line continuations or
1843 /// in `toggle comments` action.
1844 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1845 Override::as_option(
1846 self.config_override().map(|o| &o.line_comments),
1847 Some(&self.language.config.line_comments),
1848 )
1849 .map_or([].as_slice(), |e| e.as_slice())
1850 }
1851
1852 /// Config for block comments for this language.
1853 pub fn block_comment(&self) -> Option<&BlockCommentConfig> {
1854 Override::as_option(
1855 self.config_override().map(|o| &o.block_comment),
1856 self.language.config.block_comment.as_ref(),
1857 )
1858 }
1859
1860 /// Config for documentation-style block comments for this language.
1861 pub fn documentation_comment(&self) -> Option<&BlockCommentConfig> {
1862 self.language.config.documentation_comment.as_ref()
1863 }
1864
1865 /// Returns additional regex patterns that act as prefix markers for creating
1866 /// boundaries during rewrapping.
1867 ///
1868 /// By default, Zed treats as paragraph and comment prefixes as boundaries.
1869 pub fn rewrap_prefixes(&self) -> &[Regex] {
1870 &self.language.config.rewrap_prefixes
1871 }
1872
1873 /// Returns a list of language-specific word characters.
1874 ///
1875 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1876 /// the purpose of actions like 'move to next word end` or whole-word search.
1877 /// It additionally accounts for language's additional word characters.
1878 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1879 Override::as_option(
1880 self.config_override().map(|o| &o.word_characters),
1881 Some(&self.language.config.word_characters),
1882 )
1883 }
1884
1885 /// Returns a list of language-specific characters that are considered part of
1886 /// a completion query.
1887 pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1888 Override::as_option(
1889 self.config_override()
1890 .map(|o| &o.completion_query_characters),
1891 Some(&self.language.config.completion_query_characters),
1892 )
1893 }
1894
1895 /// Returns whether to prefer snippet `label` over `new_text` to replace text when
1896 /// completion is accepted.
1897 ///
1898 /// In cases like when cursor is in string or renaming existing function,
1899 /// you don't want to expand function signature instead just want function name
1900 /// to replace existing one.
1901 pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
1902 self.config_override()
1903 .and_then(|o| o.prefer_label_for_snippet)
1904 .unwrap_or(false)
1905 }
1906
1907 /// Returns a list of bracket pairs for a given language with an additional
1908 /// piece of information about whether the particular bracket pair is currently active for a given language.
1909 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1910 let mut disabled_ids = self
1911 .config_override()
1912 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1913 self.language
1914 .config
1915 .brackets
1916 .pairs
1917 .iter()
1918 .enumerate()
1919 .map(move |(ix, bracket)| {
1920 let mut is_enabled = true;
1921 if let Some(next_disabled_ix) = disabled_ids.first()
1922 && ix == *next_disabled_ix as usize
1923 {
1924 disabled_ids = &disabled_ids[1..];
1925 is_enabled = false;
1926 }
1927 (bracket, is_enabled)
1928 })
1929 }
1930
1931 pub fn should_autoclose_before(&self, c: char) -> bool {
1932 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1933 }
1934
1935 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1936 let config = &self.language.config;
1937 let opt_in_servers = &config.scope_opt_in_language_servers;
1938 if opt_in_servers.contains(name) {
1939 if let Some(over) = self.config_override() {
1940 over.opt_into_language_servers.contains(name)
1941 } else {
1942 false
1943 }
1944 } else {
1945 true
1946 }
1947 }
1948
1949 pub fn override_name(&self) -> Option<&str> {
1950 let id = self.override_id?;
1951 let grammar = self.language.grammar.as_ref()?;
1952 let override_config = grammar.override_config.as_ref()?;
1953 override_config.values.get(&id).map(|e| e.name.as_str())
1954 }
1955
1956 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1957 let id = self.override_id?;
1958 let grammar = self.language.grammar.as_ref()?;
1959 let override_config = grammar.override_config.as_ref()?;
1960 override_config.values.get(&id).map(|e| &e.value)
1961 }
1962}
1963
1964impl Hash for Language {
1965 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1966 self.id.hash(state)
1967 }
1968}
1969
1970impl PartialEq for Language {
1971 fn eq(&self, other: &Self) -> bool {
1972 self.id.eq(&other.id)
1973 }
1974}
1975
1976impl Eq for Language {}
1977
1978impl Debug for Language {
1979 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1980 f.debug_struct("Language")
1981 .field("name", &self.config.name)
1982 .finish()
1983 }
1984}
1985
1986impl Grammar {
1987 pub fn id(&self) -> GrammarId {
1988 self.id
1989 }
1990
1991 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1992 with_parser(|parser| {
1993 parser
1994 .set_language(&self.ts_language)
1995 .expect("incompatible grammar");
1996 let mut chunks = text.chunks_in_range(0..text.len());
1997 parser
1998 .parse_with_options(
1999 &mut move |offset, _| {
2000 chunks.seek(offset);
2001 chunks.next().unwrap_or("").as_bytes()
2002 },
2003 old_tree.as_ref(),
2004 None,
2005 )
2006 .unwrap()
2007 })
2008 }
2009
2010 pub fn highlight_map(&self) -> HighlightMap {
2011 self.highlight_map.lock().clone()
2012 }
2013
2014 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
2015 let capture_id = self
2016 .highlights_query
2017 .as_ref()?
2018 .capture_index_for_name(name)?;
2019 Some(self.highlight_map.lock().get(capture_id))
2020 }
2021
2022 pub fn debug_variables_config(&self) -> Option<&DebugVariablesConfig> {
2023 self.debug_variables_config.as_ref()
2024 }
2025}
2026
2027impl CodeLabel {
2028 pub fn fallback_for_completion(
2029 item: &lsp::CompletionItem,
2030 language: Option<&Language>,
2031 ) -> Self {
2032 let highlight_id = item.kind.and_then(|kind| {
2033 let grammar = language?.grammar()?;
2034 use lsp::CompletionItemKind as Kind;
2035 match kind {
2036 Kind::CLASS => grammar.highlight_id_for_name("type"),
2037 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
2038 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
2039 Kind::ENUM => grammar
2040 .highlight_id_for_name("enum")
2041 .or_else(|| grammar.highlight_id_for_name("type")),
2042 Kind::ENUM_MEMBER => grammar
2043 .highlight_id_for_name("variant")
2044 .or_else(|| grammar.highlight_id_for_name("property")),
2045 Kind::FIELD => grammar.highlight_id_for_name("property"),
2046 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
2047 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
2048 Kind::METHOD => grammar
2049 .highlight_id_for_name("function.method")
2050 .or_else(|| grammar.highlight_id_for_name("function")),
2051 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
2052 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
2053 Kind::STRUCT => grammar.highlight_id_for_name("type"),
2054 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
2055 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
2056 _ => None,
2057 }
2058 });
2059
2060 let label = &item.label;
2061 let label_length = label.len();
2062 let runs = highlight_id
2063 .map(|highlight_id| vec![(0..label_length, highlight_id)])
2064 .unwrap_or_default();
2065 let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
2066 format!("{label} {detail}")
2067 } else if let Some(description) = item
2068 .label_details
2069 .as_ref()
2070 .and_then(|label_details| label_details.description.as_deref())
2071 .filter(|description| description != label)
2072 {
2073 format!("{label} {description}")
2074 } else {
2075 label.clone()
2076 };
2077 let filter_range = item
2078 .filter_text
2079 .as_deref()
2080 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2081 .unwrap_or(0..label_length);
2082 Self {
2083 text,
2084 runs,
2085 filter_range,
2086 }
2087 }
2088
2089 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
2090 let filter_range = filter_text
2091 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2092 .unwrap_or(0..text.len());
2093 Self {
2094 runs: Vec::new(),
2095 filter_range,
2096 text,
2097 }
2098 }
2099
2100 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2101 let start_ix = self.text.len();
2102 self.text.push_str(text);
2103 let end_ix = self.text.len();
2104 if let Some(highlight) = highlight {
2105 self.runs.push((start_ix..end_ix, highlight));
2106 }
2107 }
2108
2109 pub fn text(&self) -> &str {
2110 self.text.as_str()
2111 }
2112
2113 pub fn filter_text(&self) -> &str {
2114 &self.text[self.filter_range.clone()]
2115 }
2116}
2117
2118impl From<String> for CodeLabel {
2119 fn from(value: String) -> Self {
2120 Self::plain(value, None)
2121 }
2122}
2123
2124impl From<&str> for CodeLabel {
2125 fn from(value: &str) -> Self {
2126 Self::plain(value.to_string(), None)
2127 }
2128}
2129
2130impl Ord for LanguageMatcher {
2131 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2132 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2133 self.first_line_pattern
2134 .as_ref()
2135 .map(Regex::as_str)
2136 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2137 })
2138 }
2139}
2140
2141impl PartialOrd for LanguageMatcher {
2142 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2143 Some(self.cmp(other))
2144 }
2145}
2146
2147impl Eq for LanguageMatcher {}
2148
2149impl PartialEq for LanguageMatcher {
2150 fn eq(&self, other: &Self) -> bool {
2151 self.path_suffixes == other.path_suffixes
2152 && self.first_line_pattern.as_ref().map(Regex::as_str)
2153 == other.first_line_pattern.as_ref().map(Regex::as_str)
2154 }
2155}
2156
2157#[cfg(any(test, feature = "test-support"))]
2158impl Default for FakeLspAdapter {
2159 fn default() -> Self {
2160 Self {
2161 name: "the-fake-language-server",
2162 capabilities: lsp::LanguageServer::full_capabilities(),
2163 initializer: None,
2164 disk_based_diagnostics_progress_token: None,
2165 initialization_options: None,
2166 disk_based_diagnostics_sources: Vec::new(),
2167 prettier_plugins: Vec::new(),
2168 language_server_binary: LanguageServerBinary {
2169 path: "/the/fake/lsp/path".into(),
2170 arguments: vec![],
2171 env: Default::default(),
2172 },
2173 label_for_completion: None,
2174 }
2175 }
2176}
2177
2178#[cfg(any(test, feature = "test-support"))]
2179#[async_trait(?Send)]
2180impl LspAdapter for FakeLspAdapter {
2181 fn name(&self) -> LanguageServerName {
2182 LanguageServerName(self.name.into())
2183 }
2184
2185 async fn check_if_user_installed(
2186 &self,
2187 _: &dyn LspAdapterDelegate,
2188 _: Option<Toolchain>,
2189 _: &AsyncApp,
2190 ) -> Option<LanguageServerBinary> {
2191 Some(self.language_server_binary.clone())
2192 }
2193
2194 fn get_language_server_command<'a>(
2195 self: Arc<Self>,
2196 _: Arc<dyn LspAdapterDelegate>,
2197 _: Option<Toolchain>,
2198 _: LanguageServerBinaryOptions,
2199 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2200 _: &'a mut AsyncApp,
2201 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2202 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2203 }
2204
2205 async fn fetch_latest_server_version(
2206 &self,
2207 _: &dyn LspAdapterDelegate,
2208 ) -> Result<Box<dyn 'static + Send + Any>> {
2209 unreachable!();
2210 }
2211
2212 async fn fetch_server_binary(
2213 &self,
2214 _: Box<dyn 'static + Send + Any>,
2215 _: PathBuf,
2216 _: &dyn LspAdapterDelegate,
2217 ) -> Result<LanguageServerBinary> {
2218 unreachable!();
2219 }
2220
2221 async fn cached_server_binary(
2222 &self,
2223 _: PathBuf,
2224 _: &dyn LspAdapterDelegate,
2225 ) -> Option<LanguageServerBinary> {
2226 unreachable!();
2227 }
2228
2229 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2230 self.disk_based_diagnostics_sources.clone()
2231 }
2232
2233 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2234 self.disk_based_diagnostics_progress_token.clone()
2235 }
2236
2237 async fn initialization_options(
2238 self: Arc<Self>,
2239 _: &dyn Fs,
2240 _: &Arc<dyn LspAdapterDelegate>,
2241 ) -> Result<Option<Value>> {
2242 Ok(self.initialization_options.clone())
2243 }
2244
2245 async fn label_for_completion(
2246 &self,
2247 item: &lsp::CompletionItem,
2248 language: &Arc<Language>,
2249 ) -> Option<CodeLabel> {
2250 let label_for_completion = self.label_for_completion.as_ref()?;
2251 label_for_completion(item, language)
2252 }
2253}
2254
2255fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2256 for (ix, name) in query.capture_names().iter().enumerate() {
2257 for (capture_name, index) in captures.iter_mut() {
2258 if capture_name == name {
2259 **index = Some(ix as u32);
2260 break;
2261 }
2262 }
2263 }
2264}
2265
2266pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2267 lsp::Position::new(point.row, point.column)
2268}
2269
2270pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2271 Unclipped(PointUtf16::new(point.line, point.character))
2272}
2273
2274pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2275 anyhow::ensure!(
2276 range.start <= range.end,
2277 "Inverted range provided to an LSP request: {:?}-{:?}",
2278 range.start,
2279 range.end
2280 );
2281 Ok(lsp::Range {
2282 start: point_to_lsp(range.start),
2283 end: point_to_lsp(range.end),
2284 })
2285}
2286
2287pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2288 let mut start = point_from_lsp(range.start);
2289 let mut end = point_from_lsp(range.end);
2290 if start > end {
2291 log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2292 mem::swap(&mut start, &mut end);
2293 }
2294 start..end
2295}
2296
2297#[cfg(test)]
2298mod tests {
2299 use super::*;
2300 use gpui::TestAppContext;
2301 use pretty_assertions::assert_matches;
2302
2303 #[gpui::test(iterations = 10)]
2304 async fn test_language_loading(cx: &mut TestAppContext) {
2305 let languages = LanguageRegistry::test(cx.executor());
2306 let languages = Arc::new(languages);
2307 languages.register_native_grammars([
2308 ("json", tree_sitter_json::LANGUAGE),
2309 ("rust", tree_sitter_rust::LANGUAGE),
2310 ]);
2311 languages.register_test_language(LanguageConfig {
2312 name: "JSON".into(),
2313 grammar: Some("json".into()),
2314 matcher: LanguageMatcher {
2315 path_suffixes: vec!["json".into()],
2316 ..Default::default()
2317 },
2318 ..Default::default()
2319 });
2320 languages.register_test_language(LanguageConfig {
2321 name: "Rust".into(),
2322 grammar: Some("rust".into()),
2323 matcher: LanguageMatcher {
2324 path_suffixes: vec!["rs".into()],
2325 ..Default::default()
2326 },
2327 ..Default::default()
2328 });
2329 assert_eq!(
2330 languages.language_names(),
2331 &[
2332 LanguageName::new("JSON"),
2333 LanguageName::new("Plain Text"),
2334 LanguageName::new("Rust"),
2335 ]
2336 );
2337
2338 let rust1 = languages.language_for_name("Rust");
2339 let rust2 = languages.language_for_name("Rust");
2340
2341 // Ensure language is still listed even if it's being loaded.
2342 assert_eq!(
2343 languages.language_names(),
2344 &[
2345 LanguageName::new("JSON"),
2346 LanguageName::new("Plain Text"),
2347 LanguageName::new("Rust"),
2348 ]
2349 );
2350
2351 let (rust1, rust2) = futures::join!(rust1, rust2);
2352 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2353
2354 // Ensure language is still listed even after loading it.
2355 assert_eq!(
2356 languages.language_names(),
2357 &[
2358 LanguageName::new("JSON"),
2359 LanguageName::new("Plain Text"),
2360 LanguageName::new("Rust"),
2361 ]
2362 );
2363
2364 // Loading an unknown language returns an error.
2365 assert!(languages.language_for_name("Unknown").await.is_err());
2366 }
2367
2368 #[gpui::test]
2369 async fn test_completion_label_omits_duplicate_data() {
2370 let regular_completion_item_1 = lsp::CompletionItem {
2371 label: "regular1".to_string(),
2372 detail: Some("detail1".to_string()),
2373 label_details: Some(lsp::CompletionItemLabelDetails {
2374 detail: None,
2375 description: Some("description 1".to_string()),
2376 }),
2377 ..lsp::CompletionItem::default()
2378 };
2379
2380 let regular_completion_item_2 = lsp::CompletionItem {
2381 label: "regular2".to_string(),
2382 label_details: Some(lsp::CompletionItemLabelDetails {
2383 detail: None,
2384 description: Some("description 2".to_string()),
2385 }),
2386 ..lsp::CompletionItem::default()
2387 };
2388
2389 let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2390 detail: Some(regular_completion_item_1.label.clone()),
2391 ..regular_completion_item_1.clone()
2392 };
2393
2394 let completion_item_with_duplicate_detail = lsp::CompletionItem {
2395 detail: Some(regular_completion_item_1.label.clone()),
2396 label_details: None,
2397 ..regular_completion_item_1.clone()
2398 };
2399
2400 let completion_item_with_duplicate_description = lsp::CompletionItem {
2401 label_details: Some(lsp::CompletionItemLabelDetails {
2402 detail: None,
2403 description: Some(regular_completion_item_2.label.clone()),
2404 }),
2405 ..regular_completion_item_2.clone()
2406 };
2407
2408 assert_eq!(
2409 CodeLabel::fallback_for_completion(®ular_completion_item_1, None).text,
2410 format!(
2411 "{} {}",
2412 regular_completion_item_1.label,
2413 regular_completion_item_1.detail.unwrap()
2414 ),
2415 "LSP completion items with both detail and label_details.description should prefer detail"
2416 );
2417 assert_eq!(
2418 CodeLabel::fallback_for_completion(®ular_completion_item_2, None).text,
2419 format!(
2420 "{} {}",
2421 regular_completion_item_2.label,
2422 regular_completion_item_2
2423 .label_details
2424 .as_ref()
2425 .unwrap()
2426 .description
2427 .as_ref()
2428 .unwrap()
2429 ),
2430 "LSP completion items without detail but with label_details.description should use that"
2431 );
2432 assert_eq!(
2433 CodeLabel::fallback_for_completion(
2434 &completion_item_with_duplicate_detail_and_proper_description,
2435 None
2436 )
2437 .text,
2438 format!(
2439 "{} {}",
2440 regular_completion_item_1.label,
2441 regular_completion_item_1
2442 .label_details
2443 .as_ref()
2444 .unwrap()
2445 .description
2446 .as_ref()
2447 .unwrap()
2448 ),
2449 "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2450 );
2451 assert_eq!(
2452 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2453 regular_completion_item_1.label,
2454 "LSP completion items with duplicate label and detail, should omit the detail"
2455 );
2456 assert_eq!(
2457 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2458 .text,
2459 regular_completion_item_2.label,
2460 "LSP completion items with duplicate label and detail, should omit the detail"
2461 );
2462 }
2463
2464 #[test]
2465 fn test_deserializing_comments_backwards_compat() {
2466 // current version of `block_comment` and `documentation_comment` work
2467 {
2468 let config: LanguageConfig = ::toml::from_str(
2469 r#"
2470 name = "Foo"
2471 block_comment = { start = "a", end = "b", prefix = "c", tab_size = 1 }
2472 documentation_comment = { start = "d", end = "e", prefix = "f", tab_size = 2 }
2473 "#,
2474 )
2475 .unwrap();
2476 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2477 assert_matches!(
2478 config.documentation_comment,
2479 Some(BlockCommentConfig { .. })
2480 );
2481
2482 let block_config = config.block_comment.unwrap();
2483 assert_eq!(block_config.start.as_ref(), "a");
2484 assert_eq!(block_config.end.as_ref(), "b");
2485 assert_eq!(block_config.prefix.as_ref(), "c");
2486 assert_eq!(block_config.tab_size, 1);
2487
2488 let doc_config = config.documentation_comment.unwrap();
2489 assert_eq!(doc_config.start.as_ref(), "d");
2490 assert_eq!(doc_config.end.as_ref(), "e");
2491 assert_eq!(doc_config.prefix.as_ref(), "f");
2492 assert_eq!(doc_config.tab_size, 2);
2493 }
2494
2495 // former `documentation` setting is read into `documentation_comment`
2496 {
2497 let config: LanguageConfig = ::toml::from_str(
2498 r#"
2499 name = "Foo"
2500 documentation = { start = "a", end = "b", prefix = "c", tab_size = 1}
2501 "#,
2502 )
2503 .unwrap();
2504 assert_matches!(
2505 config.documentation_comment,
2506 Some(BlockCommentConfig { .. })
2507 );
2508
2509 let config = config.documentation_comment.unwrap();
2510 assert_eq!(config.start.as_ref(), "a");
2511 assert_eq!(config.end.as_ref(), "b");
2512 assert_eq!(config.prefix.as_ref(), "c");
2513 assert_eq!(config.tab_size, 1);
2514 }
2515
2516 // old block_comment format is read into BlockCommentConfig
2517 {
2518 let config: LanguageConfig = ::toml::from_str(
2519 r#"
2520 name = "Foo"
2521 block_comment = ["a", "b"]
2522 "#,
2523 )
2524 .unwrap();
2525 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2526
2527 let config = config.block_comment.unwrap();
2528 assert_eq!(config.start.as_ref(), "a");
2529 assert_eq!(config.end.as_ref(), "b");
2530 assert_eq!(config.prefix.as_ref(), "");
2531 assert_eq!(config.tab_size, 0);
2532 }
2533 }
2534}