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