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}
704
705#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
706pub struct LanguageMatcher {
707 /// 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`.
708 #[serde(default)]
709 pub path_suffixes: Vec<String>,
710 /// A regex pattern that determines whether the language should be assigned to a file or not.
711 #[serde(
712 default,
713 serialize_with = "serialize_regex",
714 deserialize_with = "deserialize_regex"
715 )]
716 #[schemars(schema_with = "regex_json_schema")]
717 pub first_line_pattern: Option<Regex>,
718}
719
720/// The configuration for JSX tag auto-closing.
721#[derive(Clone, Deserialize, JsonSchema)]
722pub struct JsxTagAutoCloseConfig {
723 /// The name of the node for a opening tag
724 pub open_tag_node_name: String,
725 /// The name of the node for an closing tag
726 pub close_tag_node_name: String,
727 /// The name of the node for a complete element with children for open and close tags
728 pub jsx_element_node_name: String,
729 /// The name of the node found within both opening and closing
730 /// tags that describes the tag name
731 pub tag_name_node_name: String,
732 /// Some grammars are smart enough to detect a closing tag
733 /// that is not valid i.e. doesn't match it's corresponding
734 /// opening tag or does not have a corresponding opening tag
735 /// This should be set to the name of the node for invalid
736 /// closing tags if the grammar contains such a node, otherwise
737 /// detecting already closed tags will not work properly
738 #[serde(default)]
739 pub erroneous_close_tag_node_name: Option<String>,
740 /// See above for erroneous_close_tag_node_name for details
741 /// This should be set if the node used for the tag name
742 /// within erroneous closing tags is different from the
743 /// normal tag name node name
744 #[serde(default)]
745 pub erroneous_close_tag_name_node_name: Option<String>,
746}
747
748/// Represents a language for the given range. Some languages (e.g. HTML)
749/// interleave several languages together, thus a single buffer might actually contain
750/// several nested scopes.
751#[derive(Clone, Debug)]
752pub struct LanguageScope {
753 language: Arc<Language>,
754 override_id: Option<u32>,
755}
756
757#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
758pub struct LanguageConfigOverride {
759 #[serde(default)]
760 pub line_comments: Override<Vec<Arc<str>>>,
761 #[serde(default)]
762 pub block_comment: Override<(Arc<str>, Arc<str>)>,
763 #[serde(skip)]
764 pub disabled_bracket_ixs: Vec<u16>,
765 #[serde(default)]
766 pub word_characters: Override<HashSet<char>>,
767 #[serde(default)]
768 pub opt_into_language_servers: Vec<LanguageServerName>,
769}
770
771#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
772#[serde(untagged)]
773pub enum Override<T> {
774 Remove { remove: bool },
775 Set(T),
776}
777
778impl<T> Default for Override<T> {
779 fn default() -> Self {
780 Override::Remove { remove: false }
781 }
782}
783
784impl<T> Override<T> {
785 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
786 match this {
787 Some(Self::Set(value)) => Some(value),
788 Some(Self::Remove { remove: true }) => None,
789 Some(Self::Remove { remove: false }) | None => original,
790 }
791 }
792}
793
794impl Default for LanguageConfig {
795 fn default() -> Self {
796 Self {
797 name: LanguageName::new(""),
798 code_fence_block_name: None,
799 grammar: None,
800 matcher: LanguageMatcher::default(),
801 brackets: Default::default(),
802 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
803 auto_indent_on_paste: None,
804 increase_indent_pattern: Default::default(),
805 decrease_indent_pattern: Default::default(),
806 autoclose_before: Default::default(),
807 line_comments: Default::default(),
808 block_comment: Default::default(),
809 scope_opt_in_language_servers: Default::default(),
810 overrides: Default::default(),
811 word_characters: Default::default(),
812 collapsed_placeholder: Default::default(),
813 hard_tabs: None,
814 tab_size: None,
815 soft_wrap: None,
816 prettier_parser_name: None,
817 hidden: false,
818 jsx_tag_auto_close: None,
819 }
820 }
821}
822
823fn auto_indent_using_last_non_empty_line_default() -> bool {
824 true
825}
826
827fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
828 let source = Option::<String>::deserialize(d)?;
829 if let Some(source) = source {
830 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
831 } else {
832 Ok(None)
833 }
834}
835
836fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
837 Schema::Object(SchemaObject {
838 instance_type: Some(InstanceType::String.into()),
839 ..Default::default()
840 })
841}
842
843fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
844where
845 S: Serializer,
846{
847 match regex {
848 Some(regex) => serializer.serialize_str(regex.as_str()),
849 None => serializer.serialize_none(),
850 }
851}
852
853#[doc(hidden)]
854#[cfg(any(test, feature = "test-support"))]
855pub struct FakeLspAdapter {
856 pub name: &'static str,
857 pub initialization_options: Option<Value>,
858 pub prettier_plugins: Vec<&'static str>,
859 pub disk_based_diagnostics_progress_token: Option<String>,
860 pub disk_based_diagnostics_sources: Vec<String>,
861 pub language_server_binary: LanguageServerBinary,
862
863 pub capabilities: lsp::ServerCapabilities,
864 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
865 pub label_for_completion: Option<
866 Box<
867 dyn 'static
868 + Send
869 + Sync
870 + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
871 >,
872 >,
873}
874
875/// Configuration of handling bracket pairs for a given language.
876///
877/// This struct includes settings for defining which pairs of characters are considered brackets and
878/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
879#[derive(Clone, Debug, Default, JsonSchema)]
880pub struct BracketPairConfig {
881 /// A list of character pairs that should be treated as brackets in the context of a given language.
882 pub pairs: Vec<BracketPair>,
883 /// A list of tree-sitter scopes for which a given bracket should not be active.
884 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
885 #[serde(skip)]
886 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
887}
888
889fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
890 Option::<Vec<BracketPairContent>>::json_schema(gen)
891}
892
893#[derive(Deserialize, JsonSchema)]
894pub struct BracketPairContent {
895 #[serde(flatten)]
896 pub bracket_pair: BracketPair,
897 #[serde(default)]
898 pub not_in: Vec<String>,
899}
900
901impl<'de> Deserialize<'de> for BracketPairConfig {
902 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
903 where
904 D: Deserializer<'de>,
905 {
906 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
907 let mut brackets = Vec::with_capacity(result.len());
908 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
909 for entry in result {
910 brackets.push(entry.bracket_pair);
911 disabled_scopes_by_bracket_ix.push(entry.not_in);
912 }
913
914 Ok(BracketPairConfig {
915 pairs: brackets,
916 disabled_scopes_by_bracket_ix,
917 })
918 }
919}
920
921/// Describes a single bracket pair and how an editor should react to e.g. inserting
922/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
923#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
924pub struct BracketPair {
925 /// Starting substring for a bracket.
926 pub start: String,
927 /// Ending substring for a bracket.
928 pub end: String,
929 /// True if `end` should be automatically inserted right after `start` characters.
930 pub close: bool,
931 /// True if selected text should be surrounded by `start` and `end` characters.
932 #[serde(default = "default_true")]
933 pub surround: bool,
934 /// True if an extra newline should be inserted while the cursor is in the middle
935 /// of that bracket pair.
936 pub newline: bool,
937}
938
939#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
940pub struct LanguageId(usize);
941
942impl LanguageId {
943 pub(crate) fn new() -> Self {
944 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
945 }
946}
947
948pub struct Language {
949 pub(crate) id: LanguageId,
950 pub(crate) config: LanguageConfig,
951 pub(crate) grammar: Option<Arc<Grammar>>,
952 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
953 pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
954}
955
956#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
957pub struct GrammarId(pub usize);
958
959impl GrammarId {
960 pub(crate) fn new() -> Self {
961 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
962 }
963}
964
965pub struct Grammar {
966 id: GrammarId,
967 pub ts_language: tree_sitter::Language,
968 pub(crate) error_query: Option<Query>,
969 pub(crate) highlights_query: Option<Query>,
970 pub(crate) brackets_config: Option<BracketsConfig>,
971 pub(crate) redactions_config: Option<RedactionConfig>,
972 pub(crate) runnable_config: Option<RunnableConfig>,
973 pub(crate) indents_config: Option<IndentConfig>,
974 pub outline_config: Option<OutlineConfig>,
975 pub text_object_config: Option<TextObjectConfig>,
976 pub embedding_config: Option<EmbeddingConfig>,
977 pub(crate) injection_config: Option<InjectionConfig>,
978 pub(crate) override_config: Option<OverrideConfig>,
979 pub(crate) highlight_map: Mutex<HighlightMap>,
980}
981
982struct IndentConfig {
983 query: Query,
984 indent_capture_ix: u32,
985 start_capture_ix: Option<u32>,
986 end_capture_ix: Option<u32>,
987 outdent_capture_ix: Option<u32>,
988}
989
990pub struct OutlineConfig {
991 pub query: Query,
992 pub item_capture_ix: u32,
993 pub name_capture_ix: u32,
994 pub context_capture_ix: Option<u32>,
995 pub extra_context_capture_ix: Option<u32>,
996 pub open_capture_ix: Option<u32>,
997 pub close_capture_ix: Option<u32>,
998 pub annotation_capture_ix: Option<u32>,
999}
1000
1001#[derive(Debug, Clone, Copy, PartialEq)]
1002pub enum TextObject {
1003 InsideFunction,
1004 AroundFunction,
1005 InsideClass,
1006 AroundClass,
1007 InsideComment,
1008 AroundComment,
1009}
1010
1011impl TextObject {
1012 pub fn from_capture_name(name: &str) -> Option<TextObject> {
1013 match name {
1014 "function.inside" => Some(TextObject::InsideFunction),
1015 "function.around" => Some(TextObject::AroundFunction),
1016 "class.inside" => Some(TextObject::InsideClass),
1017 "class.around" => Some(TextObject::AroundClass),
1018 "comment.inside" => Some(TextObject::InsideComment),
1019 "comment.around" => Some(TextObject::AroundComment),
1020 _ => None,
1021 }
1022 }
1023
1024 pub fn around(&self) -> Option<Self> {
1025 match self {
1026 TextObject::InsideFunction => Some(TextObject::AroundFunction),
1027 TextObject::InsideClass => Some(TextObject::AroundClass),
1028 TextObject::InsideComment => Some(TextObject::AroundComment),
1029 _ => None,
1030 }
1031 }
1032}
1033
1034pub struct TextObjectConfig {
1035 pub query: Query,
1036 pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1037}
1038
1039#[derive(Debug)]
1040pub struct EmbeddingConfig {
1041 pub query: Query,
1042 pub item_capture_ix: u32,
1043 pub name_capture_ix: Option<u32>,
1044 pub context_capture_ix: Option<u32>,
1045 pub collapse_capture_ix: Option<u32>,
1046 pub keep_capture_ix: Option<u32>,
1047}
1048
1049struct InjectionConfig {
1050 query: Query,
1051 content_capture_ix: u32,
1052 language_capture_ix: Option<u32>,
1053 patterns: Vec<InjectionPatternConfig>,
1054}
1055
1056struct RedactionConfig {
1057 pub query: Query,
1058 pub redaction_capture_ix: u32,
1059}
1060
1061#[derive(Clone, Debug, PartialEq)]
1062enum RunnableCapture {
1063 Named(SharedString),
1064 Run,
1065}
1066
1067struct RunnableConfig {
1068 pub query: Query,
1069 /// A mapping from capture indice to capture kind
1070 pub extra_captures: Vec<RunnableCapture>,
1071}
1072
1073struct OverrideConfig {
1074 query: Query,
1075 values: HashMap<u32, OverrideEntry>,
1076}
1077
1078#[derive(Debug)]
1079struct OverrideEntry {
1080 name: String,
1081 range_is_inclusive: bool,
1082 value: LanguageConfigOverride,
1083}
1084
1085#[derive(Default, Clone)]
1086struct InjectionPatternConfig {
1087 language: Option<Box<str>>,
1088 combined: bool,
1089}
1090
1091struct BracketsConfig {
1092 query: Query,
1093 open_capture_ix: u32,
1094 close_capture_ix: u32,
1095 patterns: Vec<BracketsPatternConfig>,
1096}
1097
1098#[derive(Clone, Debug, Default)]
1099struct BracketsPatternConfig {
1100 newline_only: bool,
1101}
1102
1103impl Language {
1104 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1105 Self::new_with_id(LanguageId::new(), config, ts_language)
1106 }
1107
1108 pub fn id(&self) -> LanguageId {
1109 self.id
1110 }
1111
1112 fn new_with_id(
1113 id: LanguageId,
1114 config: LanguageConfig,
1115 ts_language: Option<tree_sitter::Language>,
1116 ) -> Self {
1117 Self {
1118 id,
1119 config,
1120 grammar: ts_language.map(|ts_language| {
1121 Arc::new(Grammar {
1122 id: GrammarId::new(),
1123 highlights_query: None,
1124 brackets_config: None,
1125 outline_config: None,
1126 text_object_config: None,
1127 embedding_config: None,
1128 indents_config: None,
1129 injection_config: None,
1130 override_config: None,
1131 redactions_config: None,
1132 runnable_config: None,
1133 error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1134 ts_language,
1135 highlight_map: Default::default(),
1136 })
1137 }),
1138 context_provider: None,
1139 toolchain: None,
1140 }
1141 }
1142
1143 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1144 self.context_provider = provider;
1145 self
1146 }
1147
1148 pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1149 self.toolchain = provider;
1150 self
1151 }
1152
1153 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1154 if let Some(query) = queries.highlights {
1155 self = self
1156 .with_highlights_query(query.as_ref())
1157 .context("Error loading highlights query")?;
1158 }
1159 if let Some(query) = queries.brackets {
1160 self = self
1161 .with_brackets_query(query.as_ref())
1162 .context("Error loading brackets query")?;
1163 }
1164 if let Some(query) = queries.indents {
1165 self = self
1166 .with_indents_query(query.as_ref())
1167 .context("Error loading indents query")?;
1168 }
1169 if let Some(query) = queries.outline {
1170 self = self
1171 .with_outline_query(query.as_ref())
1172 .context("Error loading outline query")?;
1173 }
1174 if let Some(query) = queries.embedding {
1175 self = self
1176 .with_embedding_query(query.as_ref())
1177 .context("Error loading embedding query")?;
1178 }
1179 if let Some(query) = queries.injections {
1180 self = self
1181 .with_injection_query(query.as_ref())
1182 .context("Error loading injection query")?;
1183 }
1184 if let Some(query) = queries.overrides {
1185 self = self
1186 .with_override_query(query.as_ref())
1187 .context("Error loading override query")?;
1188 }
1189 if let Some(query) = queries.redactions {
1190 self = self
1191 .with_redaction_query(query.as_ref())
1192 .context("Error loading redaction query")?;
1193 }
1194 if let Some(query) = queries.runnables {
1195 self = self
1196 .with_runnable_query(query.as_ref())
1197 .context("Error loading runnables query")?;
1198 }
1199 if let Some(query) = queries.text_objects {
1200 self = self
1201 .with_text_object_query(query.as_ref())
1202 .context("Error loading textobject query")?;
1203 }
1204 Ok(self)
1205 }
1206
1207 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1208 let grammar = self
1209 .grammar_mut()
1210 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1211 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1212 Ok(self)
1213 }
1214
1215 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1216 let grammar = self
1217 .grammar_mut()
1218 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1219
1220 let query = Query::new(&grammar.ts_language, source)?;
1221 let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1222
1223 for name in query.capture_names().iter() {
1224 let kind = if *name == "run" {
1225 RunnableCapture::Run
1226 } else {
1227 RunnableCapture::Named(name.to_string().into())
1228 };
1229 extra_captures.push(kind);
1230 }
1231
1232 grammar.runnable_config = Some(RunnableConfig {
1233 extra_captures,
1234 query,
1235 });
1236
1237 Ok(self)
1238 }
1239
1240 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1241 let grammar = self
1242 .grammar_mut()
1243 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1244 let query = Query::new(&grammar.ts_language, source)?;
1245 let mut item_capture_ix = None;
1246 let mut name_capture_ix = None;
1247 let mut context_capture_ix = None;
1248 let mut extra_context_capture_ix = None;
1249 let mut open_capture_ix = None;
1250 let mut close_capture_ix = None;
1251 let mut annotation_capture_ix = None;
1252 get_capture_indices(
1253 &query,
1254 &mut [
1255 ("item", &mut item_capture_ix),
1256 ("name", &mut name_capture_ix),
1257 ("context", &mut context_capture_ix),
1258 ("context.extra", &mut extra_context_capture_ix),
1259 ("open", &mut open_capture_ix),
1260 ("close", &mut close_capture_ix),
1261 ("annotation", &mut annotation_capture_ix),
1262 ],
1263 );
1264 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1265 grammar.outline_config = Some(OutlineConfig {
1266 query,
1267 item_capture_ix,
1268 name_capture_ix,
1269 context_capture_ix,
1270 extra_context_capture_ix,
1271 open_capture_ix,
1272 close_capture_ix,
1273 annotation_capture_ix,
1274 });
1275 }
1276 Ok(self)
1277 }
1278
1279 pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1280 let grammar = self
1281 .grammar_mut()
1282 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1283 let query = Query::new(&grammar.ts_language, source)?;
1284
1285 let mut text_objects_by_capture_ix = Vec::new();
1286 for (ix, name) in query.capture_names().iter().enumerate() {
1287 if let Some(text_object) = TextObject::from_capture_name(name) {
1288 text_objects_by_capture_ix.push((ix as u32, text_object));
1289 }
1290 }
1291
1292 grammar.text_object_config = Some(TextObjectConfig {
1293 query,
1294 text_objects_by_capture_ix,
1295 });
1296 Ok(self)
1297 }
1298
1299 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1300 let grammar = self
1301 .grammar_mut()
1302 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1303 let query = Query::new(&grammar.ts_language, source)?;
1304 let mut item_capture_ix = None;
1305 let mut name_capture_ix = None;
1306 let mut context_capture_ix = None;
1307 let mut collapse_capture_ix = None;
1308 let mut keep_capture_ix = None;
1309 get_capture_indices(
1310 &query,
1311 &mut [
1312 ("item", &mut item_capture_ix),
1313 ("name", &mut name_capture_ix),
1314 ("context", &mut context_capture_ix),
1315 ("keep", &mut keep_capture_ix),
1316 ("collapse", &mut collapse_capture_ix),
1317 ],
1318 );
1319 if let Some(item_capture_ix) = item_capture_ix {
1320 grammar.embedding_config = Some(EmbeddingConfig {
1321 query,
1322 item_capture_ix,
1323 name_capture_ix,
1324 context_capture_ix,
1325 collapse_capture_ix,
1326 keep_capture_ix,
1327 });
1328 }
1329 Ok(self)
1330 }
1331
1332 pub fn with_brackets_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 open_capture_ix = None;
1338 let mut close_capture_ix = None;
1339 get_capture_indices(
1340 &query,
1341 &mut [
1342 ("open", &mut open_capture_ix),
1343 ("close", &mut close_capture_ix),
1344 ],
1345 );
1346 let patterns = (0..query.pattern_count())
1347 .map(|ix| {
1348 let mut config = BracketsPatternConfig::default();
1349 for setting in query.property_settings(ix) {
1350 match setting.key.as_ref() {
1351 "newline.only" => config.newline_only = true,
1352 _ => {}
1353 }
1354 }
1355 config
1356 })
1357 .collect();
1358 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1359 grammar.brackets_config = Some(BracketsConfig {
1360 query,
1361 open_capture_ix,
1362 close_capture_ix,
1363 patterns,
1364 });
1365 }
1366 Ok(self)
1367 }
1368
1369 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1370 let grammar = self
1371 .grammar_mut()
1372 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1373 let query = Query::new(&grammar.ts_language, source)?;
1374 let mut indent_capture_ix = None;
1375 let mut start_capture_ix = None;
1376 let mut end_capture_ix = None;
1377 let mut outdent_capture_ix = None;
1378 get_capture_indices(
1379 &query,
1380 &mut [
1381 ("indent", &mut indent_capture_ix),
1382 ("start", &mut start_capture_ix),
1383 ("end", &mut end_capture_ix),
1384 ("outdent", &mut outdent_capture_ix),
1385 ],
1386 );
1387 if let Some(indent_capture_ix) = indent_capture_ix {
1388 grammar.indents_config = Some(IndentConfig {
1389 query,
1390 indent_capture_ix,
1391 start_capture_ix,
1392 end_capture_ix,
1393 outdent_capture_ix,
1394 });
1395 }
1396 Ok(self)
1397 }
1398
1399 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1400 let grammar = self
1401 .grammar_mut()
1402 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1403 let query = Query::new(&grammar.ts_language, source)?;
1404 let mut language_capture_ix = None;
1405 let mut injection_language_capture_ix = None;
1406 let mut content_capture_ix = None;
1407 let mut injection_content_capture_ix = None;
1408 get_capture_indices(
1409 &query,
1410 &mut [
1411 ("language", &mut language_capture_ix),
1412 ("injection.language", &mut injection_language_capture_ix),
1413 ("content", &mut content_capture_ix),
1414 ("injection.content", &mut injection_content_capture_ix),
1415 ],
1416 );
1417 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1418 (None, Some(ix)) => Some(ix),
1419 (Some(_), Some(_)) => {
1420 return Err(anyhow!(
1421 "both language and injection.language captures are present"
1422 ));
1423 }
1424 _ => language_capture_ix,
1425 };
1426 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1427 (None, Some(ix)) => Some(ix),
1428 (Some(_), Some(_)) => {
1429 return Err(anyhow!(
1430 "both content and injection.content captures are present"
1431 ));
1432 }
1433 _ => content_capture_ix,
1434 };
1435 let patterns = (0..query.pattern_count())
1436 .map(|ix| {
1437 let mut config = InjectionPatternConfig::default();
1438 for setting in query.property_settings(ix) {
1439 match setting.key.as_ref() {
1440 "language" | "injection.language" => {
1441 config.language.clone_from(&setting.value);
1442 }
1443 "combined" | "injection.combined" => {
1444 config.combined = true;
1445 }
1446 _ => {}
1447 }
1448 }
1449 config
1450 })
1451 .collect();
1452 if let Some(content_capture_ix) = content_capture_ix {
1453 grammar.injection_config = Some(InjectionConfig {
1454 query,
1455 language_capture_ix,
1456 content_capture_ix,
1457 patterns,
1458 });
1459 }
1460 Ok(self)
1461 }
1462
1463 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1464 let query = {
1465 let grammar = self
1466 .grammar
1467 .as_ref()
1468 .ok_or_else(|| anyhow!("no grammar for language"))?;
1469 Query::new(&grammar.ts_language, source)?
1470 };
1471
1472 let mut override_configs_by_id = HashMap::default();
1473 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1474 let mut range_is_inclusive = false;
1475 if name.starts_with('_') {
1476 continue;
1477 }
1478 if let Some(prefix) = name.strip_suffix(".inclusive") {
1479 name = prefix;
1480 range_is_inclusive = true;
1481 }
1482
1483 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1484 for server_name in &value.opt_into_language_servers {
1485 if !self
1486 .config
1487 .scope_opt_in_language_servers
1488 .contains(server_name)
1489 {
1490 util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1491 }
1492 }
1493
1494 override_configs_by_id.insert(
1495 ix as u32,
1496 OverrideEntry {
1497 name: name.to_string(),
1498 range_is_inclusive,
1499 value,
1500 },
1501 );
1502 }
1503
1504 let referenced_override_names = self.config.overrides.keys().chain(
1505 self.config
1506 .brackets
1507 .disabled_scopes_by_bracket_ix
1508 .iter()
1509 .flatten(),
1510 );
1511
1512 for referenced_name in referenced_override_names {
1513 if !override_configs_by_id
1514 .values()
1515 .any(|entry| entry.name == *referenced_name)
1516 {
1517 Err(anyhow!(
1518 "language {:?} has overrides in config not in query: {referenced_name:?}",
1519 self.config.name
1520 ))?;
1521 }
1522 }
1523
1524 for entry in override_configs_by_id.values_mut() {
1525 entry.value.disabled_bracket_ixs = self
1526 .config
1527 .brackets
1528 .disabled_scopes_by_bracket_ix
1529 .iter()
1530 .enumerate()
1531 .filter_map(|(ix, disabled_scope_names)| {
1532 if disabled_scope_names.contains(&entry.name) {
1533 Some(ix as u16)
1534 } else {
1535 None
1536 }
1537 })
1538 .collect();
1539 }
1540
1541 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1542
1543 let grammar = self
1544 .grammar_mut()
1545 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1546 grammar.override_config = Some(OverrideConfig {
1547 query,
1548 values: override_configs_by_id,
1549 });
1550 Ok(self)
1551 }
1552
1553 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1554 let grammar = self
1555 .grammar_mut()
1556 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1557
1558 let query = Query::new(&grammar.ts_language, source)?;
1559 let mut redaction_capture_ix = None;
1560 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1561
1562 if let Some(redaction_capture_ix) = redaction_capture_ix {
1563 grammar.redactions_config = Some(RedactionConfig {
1564 query,
1565 redaction_capture_ix,
1566 });
1567 }
1568
1569 Ok(self)
1570 }
1571
1572 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1573 Arc::get_mut(self.grammar.as_mut()?)
1574 }
1575
1576 pub fn name(&self) -> LanguageName {
1577 self.config.name.clone()
1578 }
1579
1580 pub fn code_fence_block_name(&self) -> Arc<str> {
1581 self.config
1582 .code_fence_block_name
1583 .clone()
1584 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1585 }
1586
1587 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1588 self.context_provider.clone()
1589 }
1590
1591 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1592 self.toolchain.clone()
1593 }
1594
1595 pub fn highlight_text<'a>(
1596 self: &'a Arc<Self>,
1597 text: &'a Rope,
1598 range: Range<usize>,
1599 ) -> Vec<(Range<usize>, HighlightId)> {
1600 let mut result = Vec::new();
1601 if let Some(grammar) = &self.grammar {
1602 let tree = grammar.parse_text(text, None);
1603 let captures =
1604 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1605 grammar.highlights_query.as_ref()
1606 });
1607 let highlight_maps = vec![grammar.highlight_map()];
1608 let mut offset = 0;
1609 for chunk in
1610 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1611 {
1612 let end_offset = offset + chunk.text.len();
1613 if let Some(highlight_id) = chunk.syntax_highlight_id {
1614 if !highlight_id.is_default() {
1615 result.push((offset..end_offset, highlight_id));
1616 }
1617 }
1618 offset = end_offset;
1619 }
1620 }
1621 result
1622 }
1623
1624 pub fn path_suffixes(&self) -> &[String] {
1625 &self.config.matcher.path_suffixes
1626 }
1627
1628 pub fn should_autoclose_before(&self, c: char) -> bool {
1629 c.is_whitespace() || self.config.autoclose_before.contains(c)
1630 }
1631
1632 pub fn set_theme(&self, theme: &SyntaxTheme) {
1633 if let Some(grammar) = self.grammar.as_ref() {
1634 if let Some(highlights_query) = &grammar.highlights_query {
1635 *grammar.highlight_map.lock() =
1636 HighlightMap::new(highlights_query.capture_names(), theme);
1637 }
1638 }
1639 }
1640
1641 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1642 self.grammar.as_ref()
1643 }
1644
1645 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1646 LanguageScope {
1647 language: self.clone(),
1648 override_id: None,
1649 }
1650 }
1651
1652 pub fn lsp_id(&self) -> String {
1653 self.config.name.lsp_id()
1654 }
1655
1656 pub fn prettier_parser_name(&self) -> Option<&str> {
1657 self.config.prettier_parser_name.as_deref()
1658 }
1659
1660 pub fn config(&self) -> &LanguageConfig {
1661 &self.config
1662 }
1663}
1664
1665impl LanguageScope {
1666 pub fn path_suffixes(&self) -> &[String] {
1667 &self.language.path_suffixes()
1668 }
1669
1670 pub fn language_name(&self) -> LanguageName {
1671 self.language.config.name.clone()
1672 }
1673
1674 pub fn collapsed_placeholder(&self) -> &str {
1675 self.language.config.collapsed_placeholder.as_ref()
1676 }
1677
1678 /// Returns line prefix that is inserted in e.g. line continuations or
1679 /// in `toggle comments` action.
1680 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1681 Override::as_option(
1682 self.config_override().map(|o| &o.line_comments),
1683 Some(&self.language.config.line_comments),
1684 )
1685 .map_or([].as_slice(), |e| e.as_slice())
1686 }
1687
1688 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1689 Override::as_option(
1690 self.config_override().map(|o| &o.block_comment),
1691 self.language.config.block_comment.as_ref(),
1692 )
1693 .map(|e| (&e.0, &e.1))
1694 }
1695
1696 /// Returns a list of language-specific word characters.
1697 ///
1698 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1699 /// the purpose of actions like 'move to next word end` or whole-word search.
1700 /// It additionally accounts for language's additional word characters.
1701 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1702 Override::as_option(
1703 self.config_override().map(|o| &o.word_characters),
1704 Some(&self.language.config.word_characters),
1705 )
1706 }
1707
1708 /// Returns a list of bracket pairs for a given language with an additional
1709 /// piece of information about whether the particular bracket pair is currently active for a given language.
1710 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1711 let mut disabled_ids = self
1712 .config_override()
1713 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1714 self.language
1715 .config
1716 .brackets
1717 .pairs
1718 .iter()
1719 .enumerate()
1720 .map(move |(ix, bracket)| {
1721 let mut is_enabled = true;
1722 if let Some(next_disabled_ix) = disabled_ids.first() {
1723 if ix == *next_disabled_ix as usize {
1724 disabled_ids = &disabled_ids[1..];
1725 is_enabled = false;
1726 }
1727 }
1728 (bracket, is_enabled)
1729 })
1730 }
1731
1732 pub fn should_autoclose_before(&self, c: char) -> bool {
1733 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1734 }
1735
1736 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1737 let config = &self.language.config;
1738 let opt_in_servers = &config.scope_opt_in_language_servers;
1739 if opt_in_servers.iter().any(|o| *o == *name) {
1740 if let Some(over) = self.config_override() {
1741 over.opt_into_language_servers.iter().any(|o| *o == *name)
1742 } else {
1743 false
1744 }
1745 } else {
1746 true
1747 }
1748 }
1749
1750 pub fn override_name(&self) -> Option<&str> {
1751 let id = self.override_id?;
1752 let grammar = self.language.grammar.as_ref()?;
1753 let override_config = grammar.override_config.as_ref()?;
1754 override_config.values.get(&id).map(|e| e.name.as_str())
1755 }
1756
1757 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1758 let id = self.override_id?;
1759 let grammar = self.language.grammar.as_ref()?;
1760 let override_config = grammar.override_config.as_ref()?;
1761 override_config.values.get(&id).map(|e| &e.value)
1762 }
1763}
1764
1765impl Hash for Language {
1766 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1767 self.id.hash(state)
1768 }
1769}
1770
1771impl PartialEq for Language {
1772 fn eq(&self, other: &Self) -> bool {
1773 self.id.eq(&other.id)
1774 }
1775}
1776
1777impl Eq for Language {}
1778
1779impl Debug for Language {
1780 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1781 f.debug_struct("Language")
1782 .field("name", &self.config.name)
1783 .finish()
1784 }
1785}
1786
1787impl Grammar {
1788 pub fn id(&self) -> GrammarId {
1789 self.id
1790 }
1791
1792 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1793 with_parser(|parser| {
1794 parser
1795 .set_language(&self.ts_language)
1796 .expect("incompatible grammar");
1797 let mut chunks = text.chunks_in_range(0..text.len());
1798 parser
1799 .parse_with_options(
1800 &mut move |offset, _| {
1801 chunks.seek(offset);
1802 chunks.next().unwrap_or("").as_bytes()
1803 },
1804 old_tree.as_ref(),
1805 None,
1806 )
1807 .unwrap()
1808 })
1809 }
1810
1811 pub fn highlight_map(&self) -> HighlightMap {
1812 self.highlight_map.lock().clone()
1813 }
1814
1815 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1816 let capture_id = self
1817 .highlights_query
1818 .as_ref()?
1819 .capture_index_for_name(name)?;
1820 Some(self.highlight_map.lock().get(capture_id))
1821 }
1822}
1823
1824impl CodeLabel {
1825 pub fn fallback_for_completion(
1826 item: &lsp::CompletionItem,
1827 language: Option<&Language>,
1828 ) -> Self {
1829 let highlight_id = item.kind.and_then(|kind| {
1830 let grammar = language?.grammar()?;
1831 use lsp::CompletionItemKind as Kind;
1832 match kind {
1833 Kind::CLASS => grammar.highlight_id_for_name("type"),
1834 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
1835 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
1836 Kind::ENUM => grammar
1837 .highlight_id_for_name("enum")
1838 .or_else(|| grammar.highlight_id_for_name("type")),
1839 Kind::FIELD => grammar.highlight_id_for_name("property"),
1840 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
1841 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
1842 Kind::METHOD => grammar
1843 .highlight_id_for_name("function.method")
1844 .or_else(|| grammar.highlight_id_for_name("function")),
1845 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
1846 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
1847 Kind::STRUCT => grammar.highlight_id_for_name("type"),
1848 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
1849 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
1850 _ => None,
1851 }
1852 });
1853
1854 let label = &item.label;
1855 let label_length = label.len();
1856 let runs = highlight_id
1857 .map(|highlight_id| vec![(0..label_length, highlight_id)])
1858 .unwrap_or_default();
1859 let text = if let Some(detail) = &item.detail {
1860 format!("{label} {detail}")
1861 } else if let Some(description) = item
1862 .label_details
1863 .as_ref()
1864 .and_then(|label_details| label_details.description.as_ref())
1865 {
1866 format!("{label} {description}")
1867 } else {
1868 label.clone()
1869 };
1870 Self {
1871 text,
1872 runs,
1873 filter_range: 0..label_length,
1874 }
1875 }
1876
1877 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1878 let mut result = Self {
1879 runs: Vec::new(),
1880 filter_range: 0..text.len(),
1881 text,
1882 };
1883 if let Some(filter_text) = filter_text {
1884 if let Some(ix) = result.text.find(filter_text) {
1885 result.filter_range = ix..ix + filter_text.len();
1886 }
1887 }
1888 result
1889 }
1890
1891 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
1892 let start_ix = self.text.len();
1893 self.text.push_str(text);
1894 let end_ix = self.text.len();
1895 if let Some(highlight) = highlight {
1896 self.runs.push((start_ix..end_ix, highlight));
1897 }
1898 }
1899
1900 pub fn text(&self) -> &str {
1901 self.text.as_str()
1902 }
1903
1904 pub fn filter_text(&self) -> &str {
1905 &self.text[self.filter_range.clone()]
1906 }
1907}
1908
1909impl From<String> for CodeLabel {
1910 fn from(value: String) -> Self {
1911 Self::plain(value, None)
1912 }
1913}
1914
1915impl From<&str> for CodeLabel {
1916 fn from(value: &str) -> Self {
1917 Self::plain(value.to_string(), None)
1918 }
1919}
1920
1921impl Ord for LanguageMatcher {
1922 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1923 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1924 self.first_line_pattern
1925 .as_ref()
1926 .map(Regex::as_str)
1927 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1928 })
1929 }
1930}
1931
1932impl PartialOrd for LanguageMatcher {
1933 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1934 Some(self.cmp(other))
1935 }
1936}
1937
1938impl Eq for LanguageMatcher {}
1939
1940impl PartialEq for LanguageMatcher {
1941 fn eq(&self, other: &Self) -> bool {
1942 self.path_suffixes == other.path_suffixes
1943 && self.first_line_pattern.as_ref().map(Regex::as_str)
1944 == other.first_line_pattern.as_ref().map(Regex::as_str)
1945 }
1946}
1947
1948#[cfg(any(test, feature = "test-support"))]
1949impl Default for FakeLspAdapter {
1950 fn default() -> Self {
1951 Self {
1952 name: "the-fake-language-server",
1953 capabilities: lsp::LanguageServer::full_capabilities(),
1954 initializer: None,
1955 disk_based_diagnostics_progress_token: None,
1956 initialization_options: None,
1957 disk_based_diagnostics_sources: Vec::new(),
1958 prettier_plugins: Vec::new(),
1959 language_server_binary: LanguageServerBinary {
1960 path: "/the/fake/lsp/path".into(),
1961 arguments: vec![],
1962 env: Default::default(),
1963 },
1964 label_for_completion: None,
1965 }
1966 }
1967}
1968
1969#[cfg(any(test, feature = "test-support"))]
1970#[async_trait(?Send)]
1971impl LspAdapter for FakeLspAdapter {
1972 fn name(&self) -> LanguageServerName {
1973 LanguageServerName(self.name.into())
1974 }
1975
1976 async fn check_if_user_installed(
1977 &self,
1978 _: &dyn LspAdapterDelegate,
1979 _: Arc<dyn LanguageToolchainStore>,
1980 _: &AsyncApp,
1981 ) -> Option<LanguageServerBinary> {
1982 Some(self.language_server_binary.clone())
1983 }
1984
1985 fn get_language_server_command<'a>(
1986 self: Arc<Self>,
1987 _: Arc<dyn LspAdapterDelegate>,
1988 _: Arc<dyn LanguageToolchainStore>,
1989 _: LanguageServerBinaryOptions,
1990 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1991 _: &'a mut AsyncApp,
1992 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1993 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1994 }
1995
1996 async fn fetch_latest_server_version(
1997 &self,
1998 _: &dyn LspAdapterDelegate,
1999 ) -> Result<Box<dyn 'static + Send + Any>> {
2000 unreachable!();
2001 }
2002
2003 async fn fetch_server_binary(
2004 &self,
2005 _: Box<dyn 'static + Send + Any>,
2006 _: PathBuf,
2007 _: &dyn LspAdapterDelegate,
2008 ) -> Result<LanguageServerBinary> {
2009 unreachable!();
2010 }
2011
2012 async fn cached_server_binary(
2013 &self,
2014 _: PathBuf,
2015 _: &dyn LspAdapterDelegate,
2016 ) -> Option<LanguageServerBinary> {
2017 unreachable!();
2018 }
2019
2020 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
2021
2022 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2023 self.disk_based_diagnostics_sources.clone()
2024 }
2025
2026 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2027 self.disk_based_diagnostics_progress_token.clone()
2028 }
2029
2030 async fn initialization_options(
2031 self: Arc<Self>,
2032 _: &dyn Fs,
2033 _: &Arc<dyn LspAdapterDelegate>,
2034 ) -> Result<Option<Value>> {
2035 Ok(self.initialization_options.clone())
2036 }
2037
2038 async fn label_for_completion(
2039 &self,
2040 item: &lsp::CompletionItem,
2041 language: &Arc<Language>,
2042 ) -> Option<CodeLabel> {
2043 let label_for_completion = self.label_for_completion.as_ref()?;
2044 label_for_completion(item, language)
2045 }
2046}
2047
2048fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2049 for (ix, name) in query.capture_names().iter().enumerate() {
2050 for (capture_name, index) in captures.iter_mut() {
2051 if capture_name == name {
2052 **index = Some(ix as u32);
2053 break;
2054 }
2055 }
2056 }
2057}
2058
2059pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2060 lsp::Position::new(point.row, point.column)
2061}
2062
2063pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2064 Unclipped(PointUtf16::new(point.line, point.character))
2065}
2066
2067pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2068 if range.start > range.end {
2069 Err(anyhow!(
2070 "Inverted range provided to an LSP request: {:?}-{:?}",
2071 range.start,
2072 range.end
2073 ))
2074 } else {
2075 Ok(lsp::Range {
2076 start: point_to_lsp(range.start),
2077 end: point_to_lsp(range.end),
2078 })
2079 }
2080}
2081
2082pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2083 let mut start = point_from_lsp(range.start);
2084 let mut end = point_from_lsp(range.end);
2085 if start > end {
2086 log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2087 mem::swap(&mut start, &mut end);
2088 }
2089 start..end
2090}
2091
2092#[cfg(test)]
2093mod tests {
2094 use super::*;
2095 use gpui::TestAppContext;
2096
2097 #[gpui::test(iterations = 10)]
2098 async fn test_language_loading(cx: &mut TestAppContext) {
2099 let languages = LanguageRegistry::test(cx.executor());
2100 let languages = Arc::new(languages);
2101 languages.register_native_grammars([
2102 ("json", tree_sitter_json::LANGUAGE),
2103 ("rust", tree_sitter_rust::LANGUAGE),
2104 ]);
2105 languages.register_test_language(LanguageConfig {
2106 name: "JSON".into(),
2107 grammar: Some("json".into()),
2108 matcher: LanguageMatcher {
2109 path_suffixes: vec!["json".into()],
2110 ..Default::default()
2111 },
2112 ..Default::default()
2113 });
2114 languages.register_test_language(LanguageConfig {
2115 name: "Rust".into(),
2116 grammar: Some("rust".into()),
2117 matcher: LanguageMatcher {
2118 path_suffixes: vec!["rs".into()],
2119 ..Default::default()
2120 },
2121 ..Default::default()
2122 });
2123 assert_eq!(
2124 languages.language_names(),
2125 &[
2126 "JSON".to_string(),
2127 "Plain Text".to_string(),
2128 "Rust".to_string(),
2129 ]
2130 );
2131
2132 let rust1 = languages.language_for_name("Rust");
2133 let rust2 = languages.language_for_name("Rust");
2134
2135 // Ensure language is still listed even if it's being loaded.
2136 assert_eq!(
2137 languages.language_names(),
2138 &[
2139 "JSON".to_string(),
2140 "Plain Text".to_string(),
2141 "Rust".to_string(),
2142 ]
2143 );
2144
2145 let (rust1, rust2) = futures::join!(rust1, rust2);
2146 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2147
2148 // Ensure language is still listed even after loading it.
2149 assert_eq!(
2150 languages.language_names(),
2151 &[
2152 "JSON".to_string(),
2153 "Plain Text".to_string(),
2154 "Rust".to_string(),
2155 ]
2156 );
2157
2158 // Loading an unknown language returns an error.
2159 assert!(languages.language_for_name("Unknown").await.is_err());
2160 }
2161}