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().clone()
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::info!(
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::info!("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::info!("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 match setting.key.as_ref() {
1517 "newline.only" => config.newline_only = true,
1518 _ => {}
1519 }
1520 }
1521 config
1522 })
1523 .collect();
1524 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1525 grammar.brackets_config = Some(BracketsConfig {
1526 query,
1527 open_capture_ix,
1528 close_capture_ix,
1529 patterns,
1530 });
1531 }
1532 Ok(self)
1533 }
1534
1535 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1536 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1537 let query = Query::new(&grammar.ts_language, source)?;
1538 let mut indent_capture_ix = None;
1539 let mut start_capture_ix = None;
1540 let mut end_capture_ix = None;
1541 let mut outdent_capture_ix = None;
1542 get_capture_indices(
1543 &query,
1544 &mut [
1545 ("indent", &mut indent_capture_ix),
1546 ("start", &mut start_capture_ix),
1547 ("end", &mut end_capture_ix),
1548 ("outdent", &mut outdent_capture_ix),
1549 ],
1550 );
1551
1552 let mut suffixed_start_captures = HashMap::default();
1553 for (ix, name) in query.capture_names().iter().enumerate() {
1554 if let Some(suffix) = name.strip_prefix("start.") {
1555 suffixed_start_captures.insert(ix as u32, suffix.to_owned().into());
1556 }
1557 }
1558
1559 if let Some(indent_capture_ix) = indent_capture_ix {
1560 grammar.indents_config = Some(IndentConfig {
1561 query,
1562 indent_capture_ix,
1563 start_capture_ix,
1564 end_capture_ix,
1565 outdent_capture_ix,
1566 suffixed_start_captures,
1567 });
1568 }
1569 Ok(self)
1570 }
1571
1572 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1573 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1574 let query = Query::new(&grammar.ts_language, source)?;
1575 let mut language_capture_ix = None;
1576 let mut injection_language_capture_ix = None;
1577 let mut content_capture_ix = None;
1578 let mut injection_content_capture_ix = None;
1579 get_capture_indices(
1580 &query,
1581 &mut [
1582 ("language", &mut language_capture_ix),
1583 ("injection.language", &mut injection_language_capture_ix),
1584 ("content", &mut content_capture_ix),
1585 ("injection.content", &mut injection_content_capture_ix),
1586 ],
1587 );
1588 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1589 (None, Some(ix)) => Some(ix),
1590 (Some(_), Some(_)) => {
1591 anyhow::bail!("both language and injection.language captures are present");
1592 }
1593 _ => language_capture_ix,
1594 };
1595 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1596 (None, Some(ix)) => Some(ix),
1597 (Some(_), Some(_)) => {
1598 anyhow::bail!("both content and injection.content captures are present")
1599 }
1600 _ => content_capture_ix,
1601 };
1602 let patterns = (0..query.pattern_count())
1603 .map(|ix| {
1604 let mut config = InjectionPatternConfig::default();
1605 for setting in query.property_settings(ix) {
1606 match setting.key.as_ref() {
1607 "language" | "injection.language" => {
1608 config.language.clone_from(&setting.value);
1609 }
1610 "combined" | "injection.combined" => {
1611 config.combined = true;
1612 }
1613 _ => {}
1614 }
1615 }
1616 config
1617 })
1618 .collect();
1619 if let Some(content_capture_ix) = content_capture_ix {
1620 grammar.injection_config = Some(InjectionConfig {
1621 query,
1622 language_capture_ix,
1623 content_capture_ix,
1624 patterns,
1625 });
1626 }
1627 Ok(self)
1628 }
1629
1630 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1631 let query = {
1632 let grammar = self.grammar.as_ref().context("no grammar for language")?;
1633 Query::new(&grammar.ts_language, source)?
1634 };
1635
1636 let mut override_configs_by_id = HashMap::default();
1637 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1638 let mut range_is_inclusive = false;
1639 if name.starts_with('_') {
1640 continue;
1641 }
1642 if let Some(prefix) = name.strip_suffix(".inclusive") {
1643 name = prefix;
1644 range_is_inclusive = true;
1645 }
1646
1647 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1648 for server_name in &value.opt_into_language_servers {
1649 if !self
1650 .config
1651 .scope_opt_in_language_servers
1652 .contains(server_name)
1653 {
1654 util::debug_panic!(
1655 "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1656 );
1657 }
1658 }
1659
1660 override_configs_by_id.insert(
1661 ix as u32,
1662 OverrideEntry {
1663 name: name.to_string(),
1664 range_is_inclusive,
1665 value,
1666 },
1667 );
1668 }
1669
1670 let referenced_override_names = self.config.overrides.keys().chain(
1671 self.config
1672 .brackets
1673 .disabled_scopes_by_bracket_ix
1674 .iter()
1675 .flatten(),
1676 );
1677
1678 for referenced_name in referenced_override_names {
1679 if !override_configs_by_id
1680 .values()
1681 .any(|entry| entry.name == *referenced_name)
1682 {
1683 anyhow::bail!(
1684 "language {:?} has overrides in config not in query: {referenced_name:?}",
1685 self.config.name
1686 );
1687 }
1688 }
1689
1690 for entry in override_configs_by_id.values_mut() {
1691 entry.value.disabled_bracket_ixs = self
1692 .config
1693 .brackets
1694 .disabled_scopes_by_bracket_ix
1695 .iter()
1696 .enumerate()
1697 .filter_map(|(ix, disabled_scope_names)| {
1698 if disabled_scope_names.contains(&entry.name) {
1699 Some(ix as u16)
1700 } else {
1701 None
1702 }
1703 })
1704 .collect();
1705 }
1706
1707 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1708
1709 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1710 grammar.override_config = Some(OverrideConfig {
1711 query,
1712 values: override_configs_by_id,
1713 });
1714 Ok(self)
1715 }
1716
1717 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1718 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1719
1720 let query = Query::new(&grammar.ts_language, source)?;
1721 let mut redaction_capture_ix = None;
1722 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1723
1724 if let Some(redaction_capture_ix) = redaction_capture_ix {
1725 grammar.redactions_config = Some(RedactionConfig {
1726 query,
1727 redaction_capture_ix,
1728 });
1729 }
1730
1731 Ok(self)
1732 }
1733
1734 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1735 Arc::get_mut(self.grammar.as_mut()?)
1736 }
1737
1738 pub fn name(&self) -> LanguageName {
1739 self.config.name.clone()
1740 }
1741 pub fn manifest(&self) -> Option<&ManifestName> {
1742 self.manifest_name.as_ref()
1743 }
1744
1745 pub fn code_fence_block_name(&self) -> Arc<str> {
1746 self.config
1747 .code_fence_block_name
1748 .clone()
1749 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1750 }
1751
1752 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1753 self.context_provider.clone()
1754 }
1755
1756 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1757 self.toolchain.clone()
1758 }
1759
1760 pub fn highlight_text<'a>(
1761 self: &'a Arc<Self>,
1762 text: &'a Rope,
1763 range: Range<usize>,
1764 ) -> Vec<(Range<usize>, HighlightId)> {
1765 let mut result = Vec::new();
1766 if let Some(grammar) = &self.grammar {
1767 let tree = grammar.parse_text(text, None);
1768 let captures =
1769 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1770 grammar.highlights_query.as_ref()
1771 });
1772 let highlight_maps = vec![grammar.highlight_map()];
1773 let mut offset = 0;
1774 for chunk in
1775 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1776 {
1777 let end_offset = offset + chunk.text.len();
1778 if let Some(highlight_id) = chunk.syntax_highlight_id
1779 && !highlight_id.is_default()
1780 {
1781 result.push((offset..end_offset, highlight_id));
1782 }
1783 offset = end_offset;
1784 }
1785 }
1786 result
1787 }
1788
1789 pub fn path_suffixes(&self) -> &[String] {
1790 &self.config.matcher.path_suffixes
1791 }
1792
1793 pub fn should_autoclose_before(&self, c: char) -> bool {
1794 c.is_whitespace() || self.config.autoclose_before.contains(c)
1795 }
1796
1797 pub fn set_theme(&self, theme: &SyntaxTheme) {
1798 if let Some(grammar) = self.grammar.as_ref()
1799 && let Some(highlights_query) = &grammar.highlights_query
1800 {
1801 *grammar.highlight_map.lock() =
1802 HighlightMap::new(highlights_query.capture_names(), theme);
1803 }
1804 }
1805
1806 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1807 self.grammar.as_ref()
1808 }
1809
1810 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1811 LanguageScope {
1812 language: self.clone(),
1813 override_id: None,
1814 }
1815 }
1816
1817 pub fn lsp_id(&self) -> String {
1818 self.config.name.lsp_id()
1819 }
1820
1821 pub fn prettier_parser_name(&self) -> Option<&str> {
1822 self.config.prettier_parser_name.as_deref()
1823 }
1824
1825 pub fn config(&self) -> &LanguageConfig {
1826 &self.config
1827 }
1828}
1829
1830impl LanguageScope {
1831 pub fn path_suffixes(&self) -> &[String] {
1832 self.language.path_suffixes()
1833 }
1834
1835 pub fn language_name(&self) -> LanguageName {
1836 self.language.config.name.clone()
1837 }
1838
1839 pub fn collapsed_placeholder(&self) -> &str {
1840 self.language.config.collapsed_placeholder.as_ref()
1841 }
1842
1843 /// Returns line prefix that is inserted in e.g. line continuations or
1844 /// in `toggle comments` action.
1845 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1846 Override::as_option(
1847 self.config_override().map(|o| &o.line_comments),
1848 Some(&self.language.config.line_comments),
1849 )
1850 .map_or([].as_slice(), |e| e.as_slice())
1851 }
1852
1853 /// Config for block comments for this language.
1854 pub fn block_comment(&self) -> Option<&BlockCommentConfig> {
1855 Override::as_option(
1856 self.config_override().map(|o| &o.block_comment),
1857 self.language.config.block_comment.as_ref(),
1858 )
1859 }
1860
1861 /// Config for documentation-style block comments for this language.
1862 pub fn documentation_comment(&self) -> Option<&BlockCommentConfig> {
1863 self.language.config.documentation_comment.as_ref()
1864 }
1865
1866 /// Returns additional regex patterns that act as prefix markers for creating
1867 /// boundaries during rewrapping.
1868 ///
1869 /// By default, Zed treats as paragraph and comment prefixes as boundaries.
1870 pub fn rewrap_prefixes(&self) -> &[Regex] {
1871 &self.language.config.rewrap_prefixes
1872 }
1873
1874 /// Returns a list of language-specific word characters.
1875 ///
1876 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1877 /// the purpose of actions like 'move to next word end` or whole-word search.
1878 /// It additionally accounts for language's additional word characters.
1879 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1880 Override::as_option(
1881 self.config_override().map(|o| &o.word_characters),
1882 Some(&self.language.config.word_characters),
1883 )
1884 }
1885
1886 /// Returns a list of language-specific characters that are considered part of
1887 /// a completion query.
1888 pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1889 Override::as_option(
1890 self.config_override()
1891 .map(|o| &o.completion_query_characters),
1892 Some(&self.language.config.completion_query_characters),
1893 )
1894 }
1895
1896 /// Returns whether to prefer snippet `label` over `new_text` to replace text when
1897 /// completion is accepted.
1898 ///
1899 /// In cases like when cursor is in string or renaming existing function,
1900 /// you don't want to expand function signature instead just want function name
1901 /// to replace existing one.
1902 pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
1903 self.config_override()
1904 .and_then(|o| o.prefer_label_for_snippet)
1905 .unwrap_or(false)
1906 }
1907
1908 /// Returns a list of bracket pairs for a given language with an additional
1909 /// piece of information about whether the particular bracket pair is currently active for a given language.
1910 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1911 let mut disabled_ids = self
1912 .config_override()
1913 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1914 self.language
1915 .config
1916 .brackets
1917 .pairs
1918 .iter()
1919 .enumerate()
1920 .map(move |(ix, bracket)| {
1921 let mut is_enabled = true;
1922 if let Some(next_disabled_ix) = disabled_ids.first()
1923 && ix == *next_disabled_ix as usize
1924 {
1925 disabled_ids = &disabled_ids[1..];
1926 is_enabled = false;
1927 }
1928 (bracket, is_enabled)
1929 })
1930 }
1931
1932 pub fn should_autoclose_before(&self, c: char) -> bool {
1933 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1934 }
1935
1936 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1937 let config = &self.language.config;
1938 let opt_in_servers = &config.scope_opt_in_language_servers;
1939 if opt_in_servers.contains(name) {
1940 if let Some(over) = self.config_override() {
1941 over.opt_into_language_servers.contains(name)
1942 } else {
1943 false
1944 }
1945 } else {
1946 true
1947 }
1948 }
1949
1950 pub fn override_name(&self) -> Option<&str> {
1951 let id = self.override_id?;
1952 let grammar = self.language.grammar.as_ref()?;
1953 let override_config = grammar.override_config.as_ref()?;
1954 override_config.values.get(&id).map(|e| e.name.as_str())
1955 }
1956
1957 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1958 let id = self.override_id?;
1959 let grammar = self.language.grammar.as_ref()?;
1960 let override_config = grammar.override_config.as_ref()?;
1961 override_config.values.get(&id).map(|e| &e.value)
1962 }
1963}
1964
1965impl Hash for Language {
1966 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1967 self.id.hash(state)
1968 }
1969}
1970
1971impl PartialEq for Language {
1972 fn eq(&self, other: &Self) -> bool {
1973 self.id.eq(&other.id)
1974 }
1975}
1976
1977impl Eq for Language {}
1978
1979impl Debug for Language {
1980 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1981 f.debug_struct("Language")
1982 .field("name", &self.config.name)
1983 .finish()
1984 }
1985}
1986
1987impl Grammar {
1988 pub fn id(&self) -> GrammarId {
1989 self.id
1990 }
1991
1992 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1993 with_parser(|parser| {
1994 parser
1995 .set_language(&self.ts_language)
1996 .expect("incompatible grammar");
1997 let mut chunks = text.chunks_in_range(0..text.len());
1998 parser
1999 .parse_with_options(
2000 &mut move |offset, _| {
2001 chunks.seek(offset);
2002 chunks.next().unwrap_or("").as_bytes()
2003 },
2004 old_tree.as_ref(),
2005 None,
2006 )
2007 .unwrap()
2008 })
2009 }
2010
2011 pub fn highlight_map(&self) -> HighlightMap {
2012 self.highlight_map.lock().clone()
2013 }
2014
2015 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
2016 let capture_id = self
2017 .highlights_query
2018 .as_ref()?
2019 .capture_index_for_name(name)?;
2020 Some(self.highlight_map.lock().get(capture_id))
2021 }
2022
2023 pub fn debug_variables_config(&self) -> Option<&DebugVariablesConfig> {
2024 self.debug_variables_config.as_ref()
2025 }
2026}
2027
2028impl CodeLabel {
2029 pub fn fallback_for_completion(
2030 item: &lsp::CompletionItem,
2031 language: Option<&Language>,
2032 ) -> Self {
2033 let highlight_id = item.kind.and_then(|kind| {
2034 let grammar = language?.grammar()?;
2035 use lsp::CompletionItemKind as Kind;
2036 match kind {
2037 Kind::CLASS => grammar.highlight_id_for_name("type"),
2038 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
2039 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
2040 Kind::ENUM => grammar
2041 .highlight_id_for_name("enum")
2042 .or_else(|| grammar.highlight_id_for_name("type")),
2043 Kind::ENUM_MEMBER => grammar
2044 .highlight_id_for_name("variant")
2045 .or_else(|| grammar.highlight_id_for_name("property")),
2046 Kind::FIELD => grammar.highlight_id_for_name("property"),
2047 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
2048 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
2049 Kind::METHOD => grammar
2050 .highlight_id_for_name("function.method")
2051 .or_else(|| grammar.highlight_id_for_name("function")),
2052 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
2053 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
2054 Kind::STRUCT => grammar.highlight_id_for_name("type"),
2055 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
2056 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
2057 _ => None,
2058 }
2059 });
2060
2061 let label = &item.label;
2062 let label_length = label.len();
2063 let runs = highlight_id
2064 .map(|highlight_id| vec![(0..label_length, highlight_id)])
2065 .unwrap_or_default();
2066 let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
2067 format!("{label} {detail}")
2068 } else if let Some(description) = item
2069 .label_details
2070 .as_ref()
2071 .and_then(|label_details| label_details.description.as_deref())
2072 .filter(|description| description != label)
2073 {
2074 format!("{label} {description}")
2075 } else {
2076 label.clone()
2077 };
2078 let filter_range = item
2079 .filter_text
2080 .as_deref()
2081 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2082 .unwrap_or(0..label_length);
2083 Self {
2084 text,
2085 runs,
2086 filter_range,
2087 }
2088 }
2089
2090 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
2091 let filter_range = filter_text
2092 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2093 .unwrap_or(0..text.len());
2094 Self {
2095 runs: Vec::new(),
2096 filter_range,
2097 text,
2098 }
2099 }
2100
2101 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2102 let start_ix = self.text.len();
2103 self.text.push_str(text);
2104 let end_ix = self.text.len();
2105 if let Some(highlight) = highlight {
2106 self.runs.push((start_ix..end_ix, highlight));
2107 }
2108 }
2109
2110 pub fn text(&self) -> &str {
2111 self.text.as_str()
2112 }
2113
2114 pub fn filter_text(&self) -> &str {
2115 &self.text[self.filter_range.clone()]
2116 }
2117}
2118
2119impl From<String> for CodeLabel {
2120 fn from(value: String) -> Self {
2121 Self::plain(value, None)
2122 }
2123}
2124
2125impl From<&str> for CodeLabel {
2126 fn from(value: &str) -> Self {
2127 Self::plain(value.to_string(), None)
2128 }
2129}
2130
2131impl Ord for LanguageMatcher {
2132 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2133 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2134 self.first_line_pattern
2135 .as_ref()
2136 .map(Regex::as_str)
2137 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2138 })
2139 }
2140}
2141
2142impl PartialOrd for LanguageMatcher {
2143 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2144 Some(self.cmp(other))
2145 }
2146}
2147
2148impl Eq for LanguageMatcher {}
2149
2150impl PartialEq for LanguageMatcher {
2151 fn eq(&self, other: &Self) -> bool {
2152 self.path_suffixes == other.path_suffixes
2153 && self.first_line_pattern.as_ref().map(Regex::as_str)
2154 == other.first_line_pattern.as_ref().map(Regex::as_str)
2155 }
2156}
2157
2158#[cfg(any(test, feature = "test-support"))]
2159impl Default for FakeLspAdapter {
2160 fn default() -> Self {
2161 Self {
2162 name: "the-fake-language-server",
2163 capabilities: lsp::LanguageServer::full_capabilities(),
2164 initializer: None,
2165 disk_based_diagnostics_progress_token: None,
2166 initialization_options: None,
2167 disk_based_diagnostics_sources: Vec::new(),
2168 prettier_plugins: Vec::new(),
2169 language_server_binary: LanguageServerBinary {
2170 path: "/the/fake/lsp/path".into(),
2171 arguments: vec![],
2172 env: Default::default(),
2173 },
2174 label_for_completion: None,
2175 }
2176 }
2177}
2178
2179#[cfg(any(test, feature = "test-support"))]
2180#[async_trait(?Send)]
2181impl LspAdapter for FakeLspAdapter {
2182 fn name(&self) -> LanguageServerName {
2183 LanguageServerName(self.name.into())
2184 }
2185
2186 async fn check_if_user_installed(
2187 &self,
2188 _: &dyn LspAdapterDelegate,
2189 _: Option<Toolchain>,
2190 _: &AsyncApp,
2191 ) -> Option<LanguageServerBinary> {
2192 Some(self.language_server_binary.clone())
2193 }
2194
2195 fn get_language_server_command<'a>(
2196 self: Arc<Self>,
2197 _: Arc<dyn LspAdapterDelegate>,
2198 _: Option<Toolchain>,
2199 _: LanguageServerBinaryOptions,
2200 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2201 _: &'a mut AsyncApp,
2202 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2203 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2204 }
2205
2206 async fn fetch_latest_server_version(
2207 &self,
2208 _: &dyn LspAdapterDelegate,
2209 ) -> Result<Box<dyn 'static + Send + Any>> {
2210 unreachable!();
2211 }
2212
2213 async fn fetch_server_binary(
2214 &self,
2215 _: Box<dyn 'static + Send + Any>,
2216 _: PathBuf,
2217 _: &dyn LspAdapterDelegate,
2218 ) -> Result<LanguageServerBinary> {
2219 unreachable!();
2220 }
2221
2222 async fn cached_server_binary(
2223 &self,
2224 _: PathBuf,
2225 _: &dyn LspAdapterDelegate,
2226 ) -> Option<LanguageServerBinary> {
2227 unreachable!();
2228 }
2229
2230 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2231 self.disk_based_diagnostics_sources.clone()
2232 }
2233
2234 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2235 self.disk_based_diagnostics_progress_token.clone()
2236 }
2237
2238 async fn initialization_options(
2239 self: Arc<Self>,
2240 _: &dyn Fs,
2241 _: &Arc<dyn LspAdapterDelegate>,
2242 ) -> Result<Option<Value>> {
2243 Ok(self.initialization_options.clone())
2244 }
2245
2246 async fn label_for_completion(
2247 &self,
2248 item: &lsp::CompletionItem,
2249 language: &Arc<Language>,
2250 ) -> Option<CodeLabel> {
2251 let label_for_completion = self.label_for_completion.as_ref()?;
2252 label_for_completion(item, language)
2253 }
2254}
2255
2256fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2257 for (ix, name) in query.capture_names().iter().enumerate() {
2258 for (capture_name, index) in captures.iter_mut() {
2259 if capture_name == name {
2260 **index = Some(ix as u32);
2261 break;
2262 }
2263 }
2264 }
2265}
2266
2267pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2268 lsp::Position::new(point.row, point.column)
2269}
2270
2271pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2272 Unclipped(PointUtf16::new(point.line, point.character))
2273}
2274
2275pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2276 anyhow::ensure!(
2277 range.start <= range.end,
2278 "Inverted range provided to an LSP request: {:?}-{:?}",
2279 range.start,
2280 range.end
2281 );
2282 Ok(lsp::Range {
2283 start: point_to_lsp(range.start),
2284 end: point_to_lsp(range.end),
2285 })
2286}
2287
2288pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2289 let mut start = point_from_lsp(range.start);
2290 let mut end = point_from_lsp(range.end);
2291 if start > end {
2292 log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2293 mem::swap(&mut start, &mut end);
2294 }
2295 start..end
2296}
2297
2298#[cfg(test)]
2299mod tests {
2300 use super::*;
2301 use gpui::TestAppContext;
2302 use pretty_assertions::assert_matches;
2303
2304 #[gpui::test(iterations = 10)]
2305 async fn test_language_loading(cx: &mut TestAppContext) {
2306 let languages = LanguageRegistry::test(cx.executor());
2307 let languages = Arc::new(languages);
2308 languages.register_native_grammars([
2309 ("json", tree_sitter_json::LANGUAGE),
2310 ("rust", tree_sitter_rust::LANGUAGE),
2311 ]);
2312 languages.register_test_language(LanguageConfig {
2313 name: "JSON".into(),
2314 grammar: Some("json".into()),
2315 matcher: LanguageMatcher {
2316 path_suffixes: vec!["json".into()],
2317 ..Default::default()
2318 },
2319 ..Default::default()
2320 });
2321 languages.register_test_language(LanguageConfig {
2322 name: "Rust".into(),
2323 grammar: Some("rust".into()),
2324 matcher: LanguageMatcher {
2325 path_suffixes: vec!["rs".into()],
2326 ..Default::default()
2327 },
2328 ..Default::default()
2329 });
2330 assert_eq!(
2331 languages.language_names(),
2332 &[
2333 LanguageName::new("JSON"),
2334 LanguageName::new("Plain Text"),
2335 LanguageName::new("Rust"),
2336 ]
2337 );
2338
2339 let rust1 = languages.language_for_name("Rust");
2340 let rust2 = languages.language_for_name("Rust");
2341
2342 // Ensure language is still listed even if it's being loaded.
2343 assert_eq!(
2344 languages.language_names(),
2345 &[
2346 LanguageName::new("JSON"),
2347 LanguageName::new("Plain Text"),
2348 LanguageName::new("Rust"),
2349 ]
2350 );
2351
2352 let (rust1, rust2) = futures::join!(rust1, rust2);
2353 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2354
2355 // Ensure language is still listed even after loading it.
2356 assert_eq!(
2357 languages.language_names(),
2358 &[
2359 LanguageName::new("JSON"),
2360 LanguageName::new("Plain Text"),
2361 LanguageName::new("Rust"),
2362 ]
2363 );
2364
2365 // Loading an unknown language returns an error.
2366 assert!(languages.language_for_name("Unknown").await.is_err());
2367 }
2368
2369 #[gpui::test]
2370 async fn test_completion_label_omits_duplicate_data() {
2371 let regular_completion_item_1 = lsp::CompletionItem {
2372 label: "regular1".to_string(),
2373 detail: Some("detail1".to_string()),
2374 label_details: Some(lsp::CompletionItemLabelDetails {
2375 detail: None,
2376 description: Some("description 1".to_string()),
2377 }),
2378 ..lsp::CompletionItem::default()
2379 };
2380
2381 let regular_completion_item_2 = lsp::CompletionItem {
2382 label: "regular2".to_string(),
2383 label_details: Some(lsp::CompletionItemLabelDetails {
2384 detail: None,
2385 description: Some("description 2".to_string()),
2386 }),
2387 ..lsp::CompletionItem::default()
2388 };
2389
2390 let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2391 detail: Some(regular_completion_item_1.label.clone()),
2392 ..regular_completion_item_1.clone()
2393 };
2394
2395 let completion_item_with_duplicate_detail = lsp::CompletionItem {
2396 detail: Some(regular_completion_item_1.label.clone()),
2397 label_details: None,
2398 ..regular_completion_item_1.clone()
2399 };
2400
2401 let completion_item_with_duplicate_description = lsp::CompletionItem {
2402 label_details: Some(lsp::CompletionItemLabelDetails {
2403 detail: None,
2404 description: Some(regular_completion_item_2.label.clone()),
2405 }),
2406 ..regular_completion_item_2.clone()
2407 };
2408
2409 assert_eq!(
2410 CodeLabel::fallback_for_completion(®ular_completion_item_1, None).text,
2411 format!(
2412 "{} {}",
2413 regular_completion_item_1.label,
2414 regular_completion_item_1.detail.unwrap()
2415 ),
2416 "LSP completion items with both detail and label_details.description should prefer detail"
2417 );
2418 assert_eq!(
2419 CodeLabel::fallback_for_completion(®ular_completion_item_2, None).text,
2420 format!(
2421 "{} {}",
2422 regular_completion_item_2.label,
2423 regular_completion_item_2
2424 .label_details
2425 .as_ref()
2426 .unwrap()
2427 .description
2428 .as_ref()
2429 .unwrap()
2430 ),
2431 "LSP completion items without detail but with label_details.description should use that"
2432 );
2433 assert_eq!(
2434 CodeLabel::fallback_for_completion(
2435 &completion_item_with_duplicate_detail_and_proper_description,
2436 None
2437 )
2438 .text,
2439 format!(
2440 "{} {}",
2441 regular_completion_item_1.label,
2442 regular_completion_item_1
2443 .label_details
2444 .as_ref()
2445 .unwrap()
2446 .description
2447 .as_ref()
2448 .unwrap()
2449 ),
2450 "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2451 );
2452 assert_eq!(
2453 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2454 regular_completion_item_1.label,
2455 "LSP completion items with duplicate label and detail, should omit the detail"
2456 );
2457 assert_eq!(
2458 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2459 .text,
2460 regular_completion_item_2.label,
2461 "LSP completion items with duplicate label and detail, should omit the detail"
2462 );
2463 }
2464
2465 #[test]
2466 fn test_deserializing_comments_backwards_compat() {
2467 // current version of `block_comment` and `documentation_comment` work
2468 {
2469 let config: LanguageConfig = ::toml::from_str(
2470 r#"
2471 name = "Foo"
2472 block_comment = { start = "a", end = "b", prefix = "c", tab_size = 1 }
2473 documentation_comment = { start = "d", end = "e", prefix = "f", tab_size = 2 }
2474 "#,
2475 )
2476 .unwrap();
2477 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2478 assert_matches!(
2479 config.documentation_comment,
2480 Some(BlockCommentConfig { .. })
2481 );
2482
2483 let block_config = config.block_comment.unwrap();
2484 assert_eq!(block_config.start.as_ref(), "a");
2485 assert_eq!(block_config.end.as_ref(), "b");
2486 assert_eq!(block_config.prefix.as_ref(), "c");
2487 assert_eq!(block_config.tab_size, 1);
2488
2489 let doc_config = config.documentation_comment.unwrap();
2490 assert_eq!(doc_config.start.as_ref(), "d");
2491 assert_eq!(doc_config.end.as_ref(), "e");
2492 assert_eq!(doc_config.prefix.as_ref(), "f");
2493 assert_eq!(doc_config.tab_size, 2);
2494 }
2495
2496 // former `documentation` setting is read into `documentation_comment`
2497 {
2498 let config: LanguageConfig = ::toml::from_str(
2499 r#"
2500 name = "Foo"
2501 documentation = { start = "a", end = "b", prefix = "c", tab_size = 1}
2502 "#,
2503 )
2504 .unwrap();
2505 assert_matches!(
2506 config.documentation_comment,
2507 Some(BlockCommentConfig { .. })
2508 );
2509
2510 let config = config.documentation_comment.unwrap();
2511 assert_eq!(config.start.as_ref(), "a");
2512 assert_eq!(config.end.as_ref(), "b");
2513 assert_eq!(config.prefix.as_ref(), "c");
2514 assert_eq!(config.tab_size, 1);
2515 }
2516
2517 // old block_comment format is read into BlockCommentConfig
2518 {
2519 let config: LanguageConfig = ::toml::from_str(
2520 r#"
2521 name = "Foo"
2522 block_comment = ["a", "b"]
2523 "#,
2524 )
2525 .unwrap();
2526 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2527
2528 let config = config.block_comment.unwrap();
2529 assert_eq!(config.start.as_ref(), "a");
2530 assert_eq!(config.end.as_ref(), "b");
2531 assert_eq!(config.prefix.as_ref(), "");
2532 assert_eq!(config.tab_size, 0);
2533 }
2534 }
2535}