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