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