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