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