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 it's API.
9mod buffer;
10mod diagnostic_set;
11mod highlight_map;
12mod language_registry;
13pub mod language_settings;
14mod outline;
15pub mod proto;
16mod syntax_map;
17
18#[cfg(test)]
19mod buffer_tests;
20pub mod markdown;
21
22use anyhow::{anyhow, Context, Result};
23use async_trait::async_trait;
24use collections::{HashMap, HashSet};
25use gpui::{AppContext, AsyncAppContext, Task};
26pub use highlight_map::HighlightMap;
27use lazy_static::lazy_static;
28use lsp::{CodeActionKind, LanguageServerBinary};
29use parking_lot::Mutex;
30use regex::Regex;
31use schemars::{
32 gen::SchemaGenerator,
33 schema::{InstanceType, Schema, SchemaObject},
34 JsonSchema,
35};
36use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
37use serde_json::Value;
38use std::{
39 any::Any,
40 cell::RefCell,
41 ffi::OsString,
42 fmt::Debug,
43 hash::Hash,
44 mem,
45 ops::Range,
46 path::{Path, PathBuf},
47 str,
48 sync::{
49 atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
50 Arc,
51 },
52};
53use syntax_map::SyntaxSnapshot;
54use theme::SyntaxTheme;
55use tree_sitter::{self, wasmtime, Query, WasmStore};
56use util::http::HttpClient;
57
58pub use buffer::Operation;
59pub use buffer::*;
60pub use diagnostic_set::DiagnosticEntry;
61pub use language_registry::{
62 LanguageQueries, LanguageRegistry, LanguageServerBinaryStatus, PendingLanguageServer,
63 QUERY_FILENAME_PREFIXES,
64};
65pub use lsp::LanguageServerId;
66pub use outline::{Outline, OutlineItem};
67pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer};
68pub use text::LineEnding;
69pub use tree_sitter::{Parser, Tree};
70
71/// Initializes the `language` crate.
72///
73/// This should be called before making use of items from the create.
74pub fn init(cx: &mut AppContext) {
75 language_settings::init(cx);
76}
77
78thread_local! {
79 static PARSER: RefCell<Parser> = {
80 let mut parser = Parser::new();
81 parser.set_wasm_store(WasmStore::new(WASM_ENGINE.clone()).unwrap()).unwrap();
82 RefCell::new(parser)
83 };
84}
85
86lazy_static! {
87 static ref NEXT_LANGUAGE_ID: AtomicUsize = Default::default();
88 static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
89 static ref WASM_ENGINE: wasmtime::Engine = wasmtime::Engine::default();
90
91 /// A shared grammar for plain text, exposed for reuse by downstream crates.
92 pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
93 LanguageConfig {
94 name: "Plain Text".into(),
95 ..Default::default()
96 },
97 None,
98 ));
99}
100
101/// Types that represent a position in a buffer, and can be converted into
102/// an LSP position, to send to a language server.
103pub trait ToLspPosition {
104 /// Converts the value into an LSP position.
105 fn to_lsp_position(self) -> lsp::Position;
106}
107
108/// A name of a language server.
109#[derive(Clone, Debug, PartialEq, Eq, Hash)]
110pub struct LanguageServerName(pub Arc<str>);
111
112/// Represents a Language Server, with certain cached sync properties.
113/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
114/// once at startup, and caches the results.
115pub struct CachedLspAdapter {
116 pub name: LanguageServerName,
117 pub short_name: &'static str,
118 pub disk_based_diagnostic_sources: Vec<String>,
119 pub disk_based_diagnostics_progress_token: Option<String>,
120 pub language_ids: HashMap<String, String>,
121 pub adapter: Arc<dyn LspAdapter>,
122 pub reinstall_attempt_count: AtomicU64,
123}
124
125impl CachedLspAdapter {
126 pub async fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
127 let name = adapter.name();
128 let short_name = adapter.short_name();
129 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
130 let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
131 let language_ids = adapter.language_ids();
132
133 Arc::new(CachedLspAdapter {
134 name,
135 short_name,
136 disk_based_diagnostic_sources,
137 disk_based_diagnostics_progress_token,
138 language_ids,
139 adapter,
140 reinstall_attempt_count: AtomicU64::new(0),
141 })
142 }
143
144 pub fn check_if_user_installed(
145 &self,
146 delegate: &Arc<dyn LspAdapterDelegate>,
147 cx: &mut AsyncAppContext,
148 ) -> Option<Task<Option<LanguageServerBinary>>> {
149 self.adapter.check_if_user_installed(delegate, cx)
150 }
151
152 pub async fn fetch_latest_server_version(
153 &self,
154 delegate: &dyn LspAdapterDelegate,
155 ) -> Result<Box<dyn 'static + Send + Any>> {
156 self.adapter.fetch_latest_server_version(delegate).await
157 }
158
159 pub fn will_fetch_server(
160 &self,
161 delegate: &Arc<dyn LspAdapterDelegate>,
162 cx: &mut AsyncAppContext,
163 ) -> Option<Task<Result<()>>> {
164 self.adapter.will_fetch_server(delegate, cx)
165 }
166
167 pub fn will_start_server(
168 &self,
169 delegate: &Arc<dyn LspAdapterDelegate>,
170 cx: &mut AsyncAppContext,
171 ) -> Option<Task<Result<()>>> {
172 self.adapter.will_start_server(delegate, cx)
173 }
174
175 pub async fn fetch_server_binary(
176 &self,
177 version: Box<dyn 'static + Send + Any>,
178 container_dir: PathBuf,
179 delegate: &dyn LspAdapterDelegate,
180 ) -> Result<LanguageServerBinary> {
181 self.adapter
182 .fetch_server_binary(version, container_dir, delegate)
183 .await
184 }
185
186 pub async fn cached_server_binary(
187 &self,
188 container_dir: PathBuf,
189 delegate: &dyn LspAdapterDelegate,
190 ) -> Option<LanguageServerBinary> {
191 self.adapter
192 .cached_server_binary(container_dir, delegate)
193 .await
194 }
195
196 pub fn can_be_reinstalled(&self) -> bool {
197 self.adapter.can_be_reinstalled()
198 }
199
200 pub async fn installation_test_binary(
201 &self,
202 container_dir: PathBuf,
203 ) -> Option<LanguageServerBinary> {
204 self.adapter.installation_test_binary(container_dir).await
205 }
206
207 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
208 self.adapter.code_action_kinds()
209 }
210
211 pub fn workspace_configuration(&self, workspace_root: &Path, cx: &mut AppContext) -> Value {
212 self.adapter.workspace_configuration(workspace_root, cx)
213 }
214
215 pub fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
216 self.adapter.process_diagnostics(params)
217 }
218
219 pub async fn process_completion(&self, completion_item: &mut lsp::CompletionItem) {
220 self.adapter.process_completion(completion_item).await
221 }
222
223 pub async fn label_for_completion(
224 &self,
225 completion_item: &lsp::CompletionItem,
226 language: &Arc<Language>,
227 ) -> Option<CodeLabel> {
228 self.adapter
229 .label_for_completion(completion_item, language)
230 .await
231 }
232
233 pub async fn label_for_symbol(
234 &self,
235 name: &str,
236 kind: lsp::SymbolKind,
237 language: &Arc<Language>,
238 ) -> Option<CodeLabel> {
239 self.adapter.label_for_symbol(name, kind, language).await
240 }
241
242 pub fn prettier_plugins(&self) -> &[&'static str] {
243 self.adapter.prettier_plugins()
244 }
245}
246
247/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
248// e.g. to display a notification or fetch data from the web.
249pub trait LspAdapterDelegate: Send + Sync {
250 fn show_notification(&self, message: &str, cx: &mut AppContext);
251 fn http_client(&self) -> Arc<dyn HttpClient>;
252 fn which_command(
253 &self,
254 command: OsString,
255 cx: &AppContext,
256 ) -> Task<Option<(PathBuf, HashMap<String, String>)>>;
257}
258
259#[async_trait]
260pub trait LspAdapter: 'static + Send + Sync {
261 fn name(&self) -> LanguageServerName;
262
263 fn short_name(&self) -> &'static str;
264
265 fn check_if_user_installed(
266 &self,
267 _: &Arc<dyn LspAdapterDelegate>,
268 _: &mut AsyncAppContext,
269 ) -> Option<Task<Option<LanguageServerBinary>>> {
270 None
271 }
272
273 async fn fetch_latest_server_version(
274 &self,
275 delegate: &dyn LspAdapterDelegate,
276 ) -> Result<Box<dyn 'static + Send + Any>>;
277
278 fn will_fetch_server(
279 &self,
280 _: &Arc<dyn LspAdapterDelegate>,
281 _: &mut AsyncAppContext,
282 ) -> Option<Task<Result<()>>> {
283 None
284 }
285
286 fn will_start_server(
287 &self,
288 _: &Arc<dyn LspAdapterDelegate>,
289 _: &mut AsyncAppContext,
290 ) -> Option<Task<Result<()>>> {
291 None
292 }
293
294 async fn fetch_server_binary(
295 &self,
296 version: Box<dyn 'static + Send + Any>,
297 container_dir: PathBuf,
298 delegate: &dyn LspAdapterDelegate,
299 ) -> Result<LanguageServerBinary>;
300
301 async fn cached_server_binary(
302 &self,
303 container_dir: PathBuf,
304 delegate: &dyn LspAdapterDelegate,
305 ) -> Option<LanguageServerBinary>;
306
307 /// Returns `true` if a language server can be reinstalled.
308 ///
309 /// If language server initialization fails, a reinstallation will be attempted unless the value returned from this method is `false`.
310 ///
311 /// Implementations that rely on software already installed on user's system
312 /// should have [`can_be_reinstalled`](Self::can_be_reinstalled) return `false`.
313 fn can_be_reinstalled(&self) -> bool {
314 true
315 }
316
317 async fn installation_test_binary(
318 &self,
319 container_dir: PathBuf,
320 ) -> Option<LanguageServerBinary>;
321
322 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
323
324 /// A callback called for each [`lsp::CompletionItem`] obtained from LSP server.
325 /// Some LspAdapter implementations might want to modify the obtained item to
326 /// change how it's displayed.
327 async fn process_completion(&self, _: &mut lsp::CompletionItem) {}
328
329 async fn label_for_completion(
330 &self,
331 _: &lsp::CompletionItem,
332 _: &Arc<Language>,
333 ) -> Option<CodeLabel> {
334 None
335 }
336
337 async fn label_for_symbol(
338 &self,
339 _: &str,
340 _: lsp::SymbolKind,
341 _: &Arc<Language>,
342 ) -> Option<CodeLabel> {
343 None
344 }
345
346 /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
347 fn initialization_options(&self) -> Option<Value> {
348 None
349 }
350
351 fn workspace_configuration(&self, _workspace_root: &Path, _cx: &mut AppContext) -> Value {
352 serde_json::json!({})
353 }
354
355 /// Returns a list of code actions supported by a given LspAdapter
356 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
357 Some(vec![
358 CodeActionKind::EMPTY,
359 CodeActionKind::QUICKFIX,
360 CodeActionKind::REFACTOR,
361 CodeActionKind::REFACTOR_EXTRACT,
362 CodeActionKind::SOURCE,
363 ])
364 }
365
366 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
367 Default::default()
368 }
369
370 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
371 None
372 }
373
374 fn language_ids(&self) -> HashMap<String, String> {
375 Default::default()
376 }
377
378 fn prettier_plugins(&self) -> &[&'static str] {
379 &[]
380 }
381}
382
383#[derive(Clone, Debug, PartialEq, Eq)]
384pub struct CodeLabel {
385 /// The text to display.
386 pub text: String,
387 /// Syntax highlighting runs.
388 pub runs: Vec<(Range<usize>, HighlightId)>,
389 /// The portion of the text that should be used in fuzzy filtering.
390 pub filter_range: Range<usize>,
391}
392
393#[derive(Clone, Deserialize, JsonSchema)]
394pub struct LanguageConfig {
395 /// Human-readable name of the language.
396 pub name: Arc<str>,
397 // The name of the grammar in a WASM bundle (experimental).
398 pub grammar: Option<Arc<str>>,
399 /// The criteria for matching this language to a given file.
400 #[serde(flatten)]
401 pub matcher: LanguageMatcher,
402 /// List of bracket types in a language.
403 #[serde(default)]
404 #[schemars(schema_with = "bracket_pair_config_json_schema")]
405 pub brackets: BracketPairConfig,
406 /// If set to true, auto indentation uses last non empty line to determine
407 /// the indentation level for a new line.
408 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
409 pub auto_indent_using_last_non_empty_line: bool,
410 /// A regex that is used to determine whether the indentation level should be
411 /// increased in the following line.
412 #[serde(default, deserialize_with = "deserialize_regex")]
413 #[schemars(schema_with = "regex_json_schema")]
414 pub increase_indent_pattern: Option<Regex>,
415 /// A regex that is used to determine whether the indentation level should be
416 /// decreased in the following line.
417 #[serde(default, deserialize_with = "deserialize_regex")]
418 #[schemars(schema_with = "regex_json_schema")]
419 pub decrease_indent_pattern: Option<Regex>,
420 /// A list of characters that trigger the automatic insertion of a closing
421 /// bracket when they immediately precede the point where an opening
422 /// bracket is inserted.
423 #[serde(default)]
424 pub autoclose_before: String,
425 /// A placeholder used internally by Semantic Index.
426 #[serde(default)]
427 pub collapsed_placeholder: String,
428 /// A line comment string that is inserted in e.g. `toggle comments` action.
429 /// A language can have multiple flavours of line comments. All of the provided line comments are
430 /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
431 #[serde(default)]
432 pub line_comments: Vec<Arc<str>>,
433 /// Starting and closing characters of a block comment.
434 #[serde(default)]
435 pub block_comment: Option<(Arc<str>, Arc<str>)>,
436 /// A list of language servers that are allowed to run on subranges of a given language.
437 #[serde(default)]
438 pub scope_opt_in_language_servers: Vec<String>,
439 #[serde(default)]
440 pub overrides: HashMap<String, LanguageConfigOverride>,
441 /// A list of characters that Zed should treat as word characters for the
442 /// purpose of features that operate on word boundaries, like 'move to next word end'
443 /// or a whole-word search in buffer search.
444 #[serde(default)]
445 pub word_characters: HashSet<char>,
446 /// The name of a Prettier parser that should be used for this language.
447 #[serde(default)]
448 pub prettier_parser_name: Option<String>,
449}
450
451#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
452pub struct LanguageMatcher {
453 /// 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`.
454 #[serde(default)]
455 pub path_suffixes: Vec<String>,
456 /// A regex pattern that determines whether the language should be assigned to a file or not.
457 #[serde(
458 default,
459 serialize_with = "serialize_regex",
460 deserialize_with = "deserialize_regex"
461 )]
462 #[schemars(schema_with = "regex_json_schema")]
463 pub first_line_pattern: Option<Regex>,
464}
465
466/// Represents a language for the given range. Some languages (e.g. HTML)
467/// interleave several languages together, thus a single buffer might actually contain
468/// several nested scopes.
469#[derive(Clone, Debug)]
470pub struct LanguageScope {
471 language: Arc<Language>,
472 override_id: Option<u32>,
473}
474
475#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
476pub struct LanguageConfigOverride {
477 #[serde(default)]
478 pub line_comments: Override<Vec<Arc<str>>>,
479 #[serde(default)]
480 pub block_comment: Override<(Arc<str>, Arc<str>)>,
481 #[serde(skip_deserializing)]
482 #[schemars(skip)]
483 pub disabled_bracket_ixs: Vec<u16>,
484 #[serde(default)]
485 pub word_characters: Override<HashSet<char>>,
486 #[serde(default)]
487 pub opt_into_language_servers: Vec<String>,
488}
489
490#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
491#[serde(untagged)]
492pub enum Override<T> {
493 Remove { remove: bool },
494 Set(T),
495}
496
497impl<T> Default for Override<T> {
498 fn default() -> Self {
499 Override::Remove { remove: false }
500 }
501}
502
503impl<T> Override<T> {
504 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
505 match this {
506 Some(Self::Set(value)) => Some(value),
507 Some(Self::Remove { remove: true }) => None,
508 Some(Self::Remove { remove: false }) | None => original,
509 }
510 }
511}
512
513impl Default for LanguageConfig {
514 fn default() -> Self {
515 Self {
516 name: "".into(),
517 grammar: None,
518 matcher: LanguageMatcher::default(),
519 brackets: Default::default(),
520 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
521 increase_indent_pattern: Default::default(),
522 decrease_indent_pattern: Default::default(),
523 autoclose_before: Default::default(),
524 line_comments: Default::default(),
525 block_comment: Default::default(),
526 scope_opt_in_language_servers: Default::default(),
527 overrides: Default::default(),
528 word_characters: Default::default(),
529 prettier_parser_name: None,
530 collapsed_placeholder: Default::default(),
531 }
532 }
533}
534
535fn auto_indent_using_last_non_empty_line_default() -> bool {
536 true
537}
538
539fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
540 let source = Option::<String>::deserialize(d)?;
541 if let Some(source) = source {
542 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
543 } else {
544 Ok(None)
545 }
546}
547
548fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
549 Schema::Object(SchemaObject {
550 instance_type: Some(InstanceType::String.into()),
551 ..Default::default()
552 })
553}
554
555fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
556where
557 S: Serializer,
558{
559 match regex {
560 Some(regex) => serializer.serialize_str(regex.as_str()),
561 None => serializer.serialize_none(),
562 }
563}
564
565#[doc(hidden)]
566#[cfg(any(test, feature = "test-support"))]
567pub struct FakeLspAdapter {
568 pub name: &'static str,
569 pub initialization_options: Option<Value>,
570 pub capabilities: lsp::ServerCapabilities,
571 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
572 pub disk_based_diagnostics_progress_token: Option<String>,
573 pub disk_based_diagnostics_sources: Vec<String>,
574 pub prettier_plugins: Vec<&'static str>,
575}
576
577/// Configuration of handling bracket pairs for a given language.
578///
579/// This struct includes settings for defining which pairs of characters are considered brackets and
580/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
581#[derive(Clone, Debug, Default, JsonSchema)]
582pub struct BracketPairConfig {
583 /// A list of character pairs that should be treated as brackets in the context of a given language.
584 pub pairs: Vec<BracketPair>,
585 /// A list of tree-sitter scopes for which a given bracket should not be active.
586 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
587 #[schemars(skip)]
588 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
589}
590
591fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
592 Option::<Vec<BracketPairContent>>::json_schema(gen)
593}
594
595#[derive(Deserialize, JsonSchema)]
596pub struct BracketPairContent {
597 #[serde(flatten)]
598 pub bracket_pair: BracketPair,
599 #[serde(default)]
600 pub not_in: Vec<String>,
601}
602
603impl<'de> Deserialize<'de> for BracketPairConfig {
604 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
605 where
606 D: Deserializer<'de>,
607 {
608 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
609 let mut brackets = Vec::with_capacity(result.len());
610 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
611 for entry in result {
612 brackets.push(entry.bracket_pair);
613 disabled_scopes_by_bracket_ix.push(entry.not_in);
614 }
615
616 Ok(BracketPairConfig {
617 pairs: brackets,
618 disabled_scopes_by_bracket_ix,
619 })
620 }
621}
622
623/// Describes a single bracket pair and how an editor should react to e.g. inserting
624/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
625#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
626pub struct BracketPair {
627 /// Starting substring for a bracket.
628 pub start: String,
629 /// Ending substring for a bracket.
630 pub end: String,
631 /// True if `end` should be automatically inserted right after `start` characters.
632 pub close: bool,
633 /// True if an extra newline should be inserted while the cursor is in the middle
634 /// of that bracket pair.
635 pub newline: bool,
636}
637
638#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
639pub(crate) struct LanguageId(usize);
640
641impl LanguageId {
642 pub(crate) fn new() -> Self {
643 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
644 }
645}
646
647pub struct Language {
648 pub(crate) id: LanguageId,
649 pub(crate) config: LanguageConfig,
650 pub(crate) grammar: Option<Arc<Grammar>>,
651 pub(crate) adapters: Vec<Arc<CachedLspAdapter>>,
652
653 #[cfg(any(test, feature = "test-support"))]
654 fake_adapter: Option<(
655 futures::channel::mpsc::UnboundedSender<lsp::FakeLanguageServer>,
656 Arc<FakeLspAdapter>,
657 )>,
658}
659
660#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
661pub struct GrammarId(pub usize);
662
663impl GrammarId {
664 pub(crate) fn new() -> Self {
665 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
666 }
667}
668
669pub struct Grammar {
670 id: GrammarId,
671 pub ts_language: tree_sitter::Language,
672 pub(crate) error_query: Query,
673 pub(crate) highlights_query: Option<Query>,
674 pub(crate) brackets_config: Option<BracketConfig>,
675 pub(crate) redactions_config: Option<RedactionConfig>,
676 pub(crate) indents_config: Option<IndentConfig>,
677 pub outline_config: Option<OutlineConfig>,
678 pub embedding_config: Option<EmbeddingConfig>,
679 pub(crate) injection_config: Option<InjectionConfig>,
680 pub(crate) override_config: Option<OverrideConfig>,
681 pub(crate) highlight_map: Mutex<HighlightMap>,
682}
683
684struct IndentConfig {
685 query: Query,
686 indent_capture_ix: u32,
687 start_capture_ix: Option<u32>,
688 end_capture_ix: Option<u32>,
689 outdent_capture_ix: Option<u32>,
690}
691
692pub struct OutlineConfig {
693 pub query: Query,
694 pub item_capture_ix: u32,
695 pub name_capture_ix: u32,
696 pub context_capture_ix: Option<u32>,
697 pub extra_context_capture_ix: Option<u32>,
698}
699
700#[derive(Debug)]
701pub struct EmbeddingConfig {
702 pub query: Query,
703 pub item_capture_ix: u32,
704 pub name_capture_ix: Option<u32>,
705 pub context_capture_ix: Option<u32>,
706 pub collapse_capture_ix: Option<u32>,
707 pub keep_capture_ix: Option<u32>,
708}
709
710struct InjectionConfig {
711 query: Query,
712 content_capture_ix: u32,
713 language_capture_ix: Option<u32>,
714 patterns: Vec<InjectionPatternConfig>,
715}
716
717struct RedactionConfig {
718 pub query: Query,
719 pub redaction_capture_ix: u32,
720}
721
722struct OverrideConfig {
723 query: Query,
724 values: HashMap<u32, (String, LanguageConfigOverride)>,
725}
726
727#[derive(Default, Clone)]
728struct InjectionPatternConfig {
729 language: Option<Box<str>>,
730 combined: bool,
731}
732
733struct BracketConfig {
734 query: Query,
735 open_capture_ix: u32,
736 close_capture_ix: u32,
737}
738
739impl Language {
740 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
741 Self::new_with_id(
742 LanguageId(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst)),
743 config,
744 ts_language,
745 )
746 }
747
748 fn new_with_id(
749 id: LanguageId,
750 config: LanguageConfig,
751 ts_language: Option<tree_sitter::Language>,
752 ) -> Self {
753 Self {
754 id,
755 config,
756 grammar: ts_language.map(|ts_language| {
757 Arc::new(Grammar {
758 id: GrammarId::new(),
759 highlights_query: None,
760 brackets_config: None,
761 outline_config: None,
762 embedding_config: None,
763 indents_config: None,
764 injection_config: None,
765 override_config: None,
766 redactions_config: None,
767 error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
768 ts_language,
769 highlight_map: Default::default(),
770 })
771 }),
772 adapters: Vec::new(),
773
774 #[cfg(any(test, feature = "test-support"))]
775 fake_adapter: None,
776 }
777 }
778
779 pub fn lsp_adapters(&self) -> &[Arc<CachedLspAdapter>] {
780 &self.adapters
781 }
782
783 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
784 if let Some(query) = queries.highlights {
785 self = self
786 .with_highlights_query(query.as_ref())
787 .context("Error loading highlights query")?;
788 }
789 if let Some(query) = queries.brackets {
790 self = self
791 .with_brackets_query(query.as_ref())
792 .context("Error loading brackets query")?;
793 }
794 if let Some(query) = queries.indents {
795 self = self
796 .with_indents_query(query.as_ref())
797 .context("Error loading indents query")?;
798 }
799 if let Some(query) = queries.outline {
800 self = self
801 .with_outline_query(query.as_ref())
802 .context("Error loading outline query")?;
803 }
804 if let Some(query) = queries.embedding {
805 self = self
806 .with_embedding_query(query.as_ref())
807 .context("Error loading embedding query")?;
808 }
809 if let Some(query) = queries.injections {
810 self = self
811 .with_injection_query(query.as_ref())
812 .context("Error loading injection query")?;
813 }
814 if let Some(query) = queries.overrides {
815 self = self
816 .with_override_query(query.as_ref())
817 .context("Error loading override query")?;
818 }
819 if let Some(query) = queries.redactions {
820 self = self
821 .with_redaction_query(query.as_ref())
822 .context("Error loading redaction query")?;
823 }
824 Ok(self)
825 }
826
827 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
828 let grammar = self.grammar_mut();
829 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
830 Ok(self)
831 }
832
833 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
834 let grammar = self.grammar_mut();
835 let query = Query::new(&grammar.ts_language, source)?;
836 let mut item_capture_ix = None;
837 let mut name_capture_ix = None;
838 let mut context_capture_ix = None;
839 let mut extra_context_capture_ix = None;
840 get_capture_indices(
841 &query,
842 &mut [
843 ("item", &mut item_capture_ix),
844 ("name", &mut name_capture_ix),
845 ("context", &mut context_capture_ix),
846 ("context.extra", &mut extra_context_capture_ix),
847 ],
848 );
849 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
850 grammar.outline_config = Some(OutlineConfig {
851 query,
852 item_capture_ix,
853 name_capture_ix,
854 context_capture_ix,
855 extra_context_capture_ix,
856 });
857 }
858 Ok(self)
859 }
860
861 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
862 let grammar = self.grammar_mut();
863 let query = Query::new(&grammar.ts_language, source)?;
864 let mut item_capture_ix = None;
865 let mut name_capture_ix = None;
866 let mut context_capture_ix = None;
867 let mut collapse_capture_ix = None;
868 let mut keep_capture_ix = None;
869 get_capture_indices(
870 &query,
871 &mut [
872 ("item", &mut item_capture_ix),
873 ("name", &mut name_capture_ix),
874 ("context", &mut context_capture_ix),
875 ("keep", &mut keep_capture_ix),
876 ("collapse", &mut collapse_capture_ix),
877 ],
878 );
879 if let Some(item_capture_ix) = item_capture_ix {
880 grammar.embedding_config = Some(EmbeddingConfig {
881 query,
882 item_capture_ix,
883 name_capture_ix,
884 context_capture_ix,
885 collapse_capture_ix,
886 keep_capture_ix,
887 });
888 }
889 Ok(self)
890 }
891
892 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
893 let grammar = self.grammar_mut();
894 let query = Query::new(&grammar.ts_language, source)?;
895 let mut open_capture_ix = None;
896 let mut close_capture_ix = None;
897 get_capture_indices(
898 &query,
899 &mut [
900 ("open", &mut open_capture_ix),
901 ("close", &mut close_capture_ix),
902 ],
903 );
904 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
905 grammar.brackets_config = Some(BracketConfig {
906 query,
907 open_capture_ix,
908 close_capture_ix,
909 });
910 }
911 Ok(self)
912 }
913
914 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
915 let grammar = self.grammar_mut();
916 let query = Query::new(&grammar.ts_language, source)?;
917 let mut indent_capture_ix = None;
918 let mut start_capture_ix = None;
919 let mut end_capture_ix = None;
920 let mut outdent_capture_ix = None;
921 get_capture_indices(
922 &query,
923 &mut [
924 ("indent", &mut indent_capture_ix),
925 ("start", &mut start_capture_ix),
926 ("end", &mut end_capture_ix),
927 ("outdent", &mut outdent_capture_ix),
928 ],
929 );
930 if let Some(indent_capture_ix) = indent_capture_ix {
931 grammar.indents_config = Some(IndentConfig {
932 query,
933 indent_capture_ix,
934 start_capture_ix,
935 end_capture_ix,
936 outdent_capture_ix,
937 });
938 }
939 Ok(self)
940 }
941
942 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
943 let grammar = self.grammar_mut();
944 let query = Query::new(&grammar.ts_language, source)?;
945 let mut language_capture_ix = None;
946 let mut content_capture_ix = None;
947 get_capture_indices(
948 &query,
949 &mut [
950 ("language", &mut language_capture_ix),
951 ("content", &mut content_capture_ix),
952 ],
953 );
954 let patterns = (0..query.pattern_count())
955 .map(|ix| {
956 let mut config = InjectionPatternConfig::default();
957 for setting in query.property_settings(ix) {
958 match setting.key.as_ref() {
959 "language" => {
960 config.language = setting.value.clone();
961 }
962 "combined" => {
963 config.combined = true;
964 }
965 _ => {}
966 }
967 }
968 config
969 })
970 .collect();
971 if let Some(content_capture_ix) = content_capture_ix {
972 grammar.injection_config = Some(InjectionConfig {
973 query,
974 language_capture_ix,
975 content_capture_ix,
976 patterns,
977 });
978 }
979 Ok(self)
980 }
981
982 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
983 let query = Query::new(&self.grammar_mut().ts_language, source)?;
984
985 let mut override_configs_by_id = HashMap::default();
986 for (ix, name) in query.capture_names().iter().enumerate() {
987 if !name.starts_with('_') {
988 let value = self.config.overrides.remove(*name).unwrap_or_default();
989 for server_name in &value.opt_into_language_servers {
990 if !self
991 .config
992 .scope_opt_in_language_servers
993 .contains(server_name)
994 {
995 util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
996 }
997 }
998
999 override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1000 }
1001 }
1002
1003 if !self.config.overrides.is_empty() {
1004 let keys = self.config.overrides.keys().collect::<Vec<_>>();
1005 Err(anyhow!(
1006 "language {:?} has overrides in config not in query: {keys:?}",
1007 self.config.name
1008 ))?;
1009 }
1010
1011 for disabled_scope_name in self
1012 .config
1013 .brackets
1014 .disabled_scopes_by_bracket_ix
1015 .iter()
1016 .flatten()
1017 {
1018 if !override_configs_by_id
1019 .values()
1020 .any(|(scope_name, _)| scope_name == disabled_scope_name)
1021 {
1022 Err(anyhow!(
1023 "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1024 self.config.name
1025 ))?;
1026 }
1027 }
1028
1029 for (name, override_config) in override_configs_by_id.values_mut() {
1030 override_config.disabled_bracket_ixs = self
1031 .config
1032 .brackets
1033 .disabled_scopes_by_bracket_ix
1034 .iter()
1035 .enumerate()
1036 .filter_map(|(ix, disabled_scope_names)| {
1037 if disabled_scope_names.contains(name) {
1038 Some(ix as u16)
1039 } else {
1040 None
1041 }
1042 })
1043 .collect();
1044 }
1045
1046 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1047 self.grammar_mut().override_config = Some(OverrideConfig {
1048 query,
1049 values: override_configs_by_id,
1050 });
1051 Ok(self)
1052 }
1053
1054 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1055 let grammar = self.grammar_mut();
1056 let query = Query::new(&grammar.ts_language, source)?;
1057 let mut redaction_capture_ix = None;
1058 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1059
1060 if let Some(redaction_capture_ix) = redaction_capture_ix {
1061 grammar.redactions_config = Some(RedactionConfig {
1062 query,
1063 redaction_capture_ix,
1064 });
1065 }
1066
1067 Ok(self)
1068 }
1069
1070 fn grammar_mut(&mut self) -> &mut Grammar {
1071 Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
1072 }
1073
1074 pub async fn with_lsp_adapters(mut self, lsp_adapters: Vec<Arc<dyn LspAdapter>>) -> Self {
1075 for adapter in lsp_adapters {
1076 self.adapters.push(CachedLspAdapter::new(adapter).await);
1077 }
1078 self
1079 }
1080
1081 #[cfg(any(test, feature = "test-support"))]
1082 pub async fn set_fake_lsp_adapter(
1083 &mut self,
1084 fake_lsp_adapter: Arc<FakeLspAdapter>,
1085 ) -> futures::channel::mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
1086 let (servers_tx, servers_rx) = futures::channel::mpsc::unbounded();
1087 self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
1088 let adapter = CachedLspAdapter::new(Arc::new(fake_lsp_adapter)).await;
1089 self.adapters = vec![adapter];
1090 servers_rx
1091 }
1092
1093 pub fn name(&self) -> Arc<str> {
1094 self.config.name.clone()
1095 }
1096
1097 pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
1098 match self.adapters.first().as_ref() {
1099 Some(adapter) => &adapter.disk_based_diagnostic_sources,
1100 None => &[],
1101 }
1102 }
1103
1104 pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
1105 for adapter in &self.adapters {
1106 let token = adapter.disk_based_diagnostics_progress_token.as_deref();
1107 if token.is_some() {
1108 return token;
1109 }
1110 }
1111
1112 None
1113 }
1114
1115 pub async fn process_completion(self: &Arc<Self>, completion: &mut lsp::CompletionItem) {
1116 for adapter in &self.adapters {
1117 adapter.process_completion(completion).await;
1118 }
1119 }
1120
1121 pub async fn label_for_completion(
1122 self: &Arc<Self>,
1123 completion: &lsp::CompletionItem,
1124 ) -> Option<CodeLabel> {
1125 self.adapters
1126 .first()
1127 .as_ref()?
1128 .label_for_completion(completion, self)
1129 .await
1130 }
1131
1132 pub async fn label_for_symbol(
1133 self: &Arc<Self>,
1134 name: &str,
1135 kind: lsp::SymbolKind,
1136 ) -> Option<CodeLabel> {
1137 self.adapters
1138 .first()
1139 .as_ref()?
1140 .label_for_symbol(name, kind, self)
1141 .await
1142 }
1143
1144 pub fn highlight_text<'a>(
1145 self: &'a Arc<Self>,
1146 text: &'a Rope,
1147 range: Range<usize>,
1148 ) -> Vec<(Range<usize>, HighlightId)> {
1149 let mut result = Vec::new();
1150 if let Some(grammar) = &self.grammar {
1151 let tree = grammar.parse_text(text, None);
1152 let captures =
1153 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1154 grammar.highlights_query.as_ref()
1155 });
1156 let highlight_maps = vec![grammar.highlight_map()];
1157 let mut offset = 0;
1158 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1159 let end_offset = offset + chunk.text.len();
1160 if let Some(highlight_id) = chunk.syntax_highlight_id {
1161 if !highlight_id.is_default() {
1162 result.push((offset..end_offset, highlight_id));
1163 }
1164 }
1165 offset = end_offset;
1166 }
1167 }
1168 result
1169 }
1170
1171 pub fn path_suffixes(&self) -> &[String] {
1172 &self.config.matcher.path_suffixes
1173 }
1174
1175 pub fn should_autoclose_before(&self, c: char) -> bool {
1176 c.is_whitespace() || self.config.autoclose_before.contains(c)
1177 }
1178
1179 pub fn set_theme(&self, theme: &SyntaxTheme) {
1180 if let Some(grammar) = self.grammar.as_ref() {
1181 if let Some(highlights_query) = &grammar.highlights_query {
1182 *grammar.highlight_map.lock() =
1183 HighlightMap::new(highlights_query.capture_names(), theme);
1184 }
1185 }
1186 }
1187
1188 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1189 self.grammar.as_ref()
1190 }
1191
1192 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1193 LanguageScope {
1194 language: self.clone(),
1195 override_id: None,
1196 }
1197 }
1198
1199 pub fn prettier_parser_name(&self) -> Option<&str> {
1200 self.config.prettier_parser_name.as_deref()
1201 }
1202}
1203
1204impl LanguageScope {
1205 pub fn collapsed_placeholder(&self) -> &str {
1206 self.language.config.collapsed_placeholder.as_ref()
1207 }
1208
1209 /// Returns line prefix that is inserted in e.g. line continuations or
1210 /// in `toggle comments` action.
1211 pub fn line_comment_prefixes(&self) -> Option<&Vec<Arc<str>>> {
1212 Override::as_option(
1213 self.config_override().map(|o| &o.line_comments),
1214 Some(&self.language.config.line_comments),
1215 )
1216 }
1217
1218 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1219 Override::as_option(
1220 self.config_override().map(|o| &o.block_comment),
1221 self.language.config.block_comment.as_ref(),
1222 )
1223 .map(|e| (&e.0, &e.1))
1224 }
1225
1226 /// Returns a list of language-specific word characters.
1227 ///
1228 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1229 /// the purpose of actions like 'move to next word end` or whole-word search.
1230 /// It additionally accounts for language's additional word characters.
1231 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1232 Override::as_option(
1233 self.config_override().map(|o| &o.word_characters),
1234 Some(&self.language.config.word_characters),
1235 )
1236 }
1237
1238 /// Returns a list of bracket pairs for a given language with an additional
1239 /// piece of information about whether the particular bracket pair is currently active for a given language.
1240 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1241 let mut disabled_ids = self
1242 .config_override()
1243 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1244 self.language
1245 .config
1246 .brackets
1247 .pairs
1248 .iter()
1249 .enumerate()
1250 .map(move |(ix, bracket)| {
1251 let mut is_enabled = true;
1252 if let Some(next_disabled_ix) = disabled_ids.first() {
1253 if ix == *next_disabled_ix as usize {
1254 disabled_ids = &disabled_ids[1..];
1255 is_enabled = false;
1256 }
1257 }
1258 (bracket, is_enabled)
1259 })
1260 }
1261
1262 pub fn should_autoclose_before(&self, c: char) -> bool {
1263 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1264 }
1265
1266 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1267 let config = &self.language.config;
1268 let opt_in_servers = &config.scope_opt_in_language_servers;
1269 if opt_in_servers.iter().any(|o| *o == *name.0) {
1270 if let Some(over) = self.config_override() {
1271 over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1272 } else {
1273 false
1274 }
1275 } else {
1276 true
1277 }
1278 }
1279
1280 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1281 let id = self.override_id?;
1282 let grammar = self.language.grammar.as_ref()?;
1283 let override_config = grammar.override_config.as_ref()?;
1284 override_config.values.get(&id).map(|e| &e.1)
1285 }
1286}
1287
1288impl Hash for Language {
1289 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1290 self.id.hash(state)
1291 }
1292}
1293
1294impl PartialEq for Language {
1295 fn eq(&self, other: &Self) -> bool {
1296 self.id.eq(&other.id)
1297 }
1298}
1299
1300impl Eq for Language {}
1301
1302impl Debug for Language {
1303 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1304 f.debug_struct("Language")
1305 .field("name", &self.config.name)
1306 .finish()
1307 }
1308}
1309
1310impl Grammar {
1311 pub fn id(&self) -> GrammarId {
1312 self.id
1313 }
1314
1315 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1316 PARSER.with(|parser| {
1317 let mut parser = parser.borrow_mut();
1318 parser
1319 .set_language(&self.ts_language)
1320 .expect("incompatible grammar");
1321 let mut chunks = text.chunks_in_range(0..text.len());
1322 parser
1323 .parse_with(
1324 &mut move |offset, _| {
1325 chunks.seek(offset);
1326 chunks.next().unwrap_or("").as_bytes()
1327 },
1328 old_tree.as_ref(),
1329 )
1330 .unwrap()
1331 })
1332 }
1333
1334 pub fn highlight_map(&self) -> HighlightMap {
1335 self.highlight_map.lock().clone()
1336 }
1337
1338 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1339 let capture_id = self
1340 .highlights_query
1341 .as_ref()?
1342 .capture_index_for_name(name)?;
1343 Some(self.highlight_map.lock().get(capture_id))
1344 }
1345}
1346
1347impl CodeLabel {
1348 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1349 let mut result = Self {
1350 runs: Vec::new(),
1351 filter_range: 0..text.len(),
1352 text,
1353 };
1354 if let Some(filter_text) = filter_text {
1355 if let Some(ix) = result.text.find(filter_text) {
1356 result.filter_range = ix..ix + filter_text.len();
1357 }
1358 }
1359 result
1360 }
1361}
1362
1363impl Ord for LanguageMatcher {
1364 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1365 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1366 self.first_line_pattern
1367 .as_ref()
1368 .map(Regex::as_str)
1369 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1370 })
1371 }
1372}
1373
1374impl PartialOrd for LanguageMatcher {
1375 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1376 Some(self.cmp(other))
1377 }
1378}
1379
1380impl Eq for LanguageMatcher {}
1381
1382impl PartialEq for LanguageMatcher {
1383 fn eq(&self, other: &Self) -> bool {
1384 self.path_suffixes == other.path_suffixes
1385 && self.first_line_pattern.as_ref().map(Regex::as_str)
1386 == other.first_line_pattern.as_ref().map(Regex::as_str)
1387 }
1388}
1389
1390#[cfg(any(test, feature = "test-support"))]
1391impl Default for FakeLspAdapter {
1392 fn default() -> Self {
1393 Self {
1394 name: "the-fake-language-server",
1395 capabilities: lsp::LanguageServer::full_capabilities(),
1396 initializer: None,
1397 disk_based_diagnostics_progress_token: None,
1398 initialization_options: None,
1399 disk_based_diagnostics_sources: Vec::new(),
1400 prettier_plugins: Vec::new(),
1401 }
1402 }
1403}
1404
1405#[cfg(any(test, feature = "test-support"))]
1406#[async_trait]
1407impl LspAdapter for Arc<FakeLspAdapter> {
1408 fn name(&self) -> LanguageServerName {
1409 LanguageServerName(self.name.into())
1410 }
1411
1412 fn short_name(&self) -> &'static str {
1413 "FakeLspAdapter"
1414 }
1415
1416 async fn fetch_latest_server_version(
1417 &self,
1418 _: &dyn LspAdapterDelegate,
1419 ) -> Result<Box<dyn 'static + Send + Any>> {
1420 unreachable!();
1421 }
1422
1423 async fn fetch_server_binary(
1424 &self,
1425 _: Box<dyn 'static + Send + Any>,
1426 _: PathBuf,
1427 _: &dyn LspAdapterDelegate,
1428 ) -> Result<LanguageServerBinary> {
1429 unreachable!();
1430 }
1431
1432 async fn cached_server_binary(
1433 &self,
1434 _: PathBuf,
1435 _: &dyn LspAdapterDelegate,
1436 ) -> Option<LanguageServerBinary> {
1437 unreachable!();
1438 }
1439
1440 async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1441 unreachable!();
1442 }
1443
1444 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1445
1446 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1447 self.disk_based_diagnostics_sources.clone()
1448 }
1449
1450 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1451 self.disk_based_diagnostics_progress_token.clone()
1452 }
1453
1454 fn initialization_options(&self) -> Option<Value> {
1455 self.initialization_options.clone()
1456 }
1457
1458 fn prettier_plugins(&self) -> &[&'static str] {
1459 &self.prettier_plugins
1460 }
1461}
1462
1463fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1464 for (ix, name) in query.capture_names().iter().enumerate() {
1465 for (capture_name, index) in captures.iter_mut() {
1466 if capture_name == name {
1467 **index = Some(ix as u32);
1468 break;
1469 }
1470 }
1471 }
1472}
1473
1474pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1475 lsp::Position::new(point.row, point.column)
1476}
1477
1478pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1479 Unclipped(PointUtf16::new(point.line, point.character))
1480}
1481
1482pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1483 lsp::Range {
1484 start: point_to_lsp(range.start),
1485 end: point_to_lsp(range.end),
1486 }
1487}
1488
1489pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1490 let mut start = point_from_lsp(range.start);
1491 let mut end = point_from_lsp(range.end);
1492 if start > end {
1493 mem::swap(&mut start, &mut end);
1494 }
1495 start..end
1496}
1497
1498#[cfg(test)]
1499mod tests {
1500 use super::*;
1501 use gpui::TestAppContext;
1502
1503 #[gpui::test(iterations = 10)]
1504 async fn test_first_line_pattern(cx: &mut TestAppContext) {
1505 let mut languages = LanguageRegistry::test();
1506
1507 languages.set_executor(cx.executor());
1508 let languages = Arc::new(languages);
1509 languages.register_test_language(LanguageConfig {
1510 name: "JavaScript".into(),
1511 matcher: LanguageMatcher {
1512 path_suffixes: vec!["js".into()],
1513 first_line_pattern: Some(Regex::new(r"\bnode\b").unwrap()),
1514 },
1515 ..Default::default()
1516 });
1517
1518 languages
1519 .language_for_file("the/script", None)
1520 .await
1521 .unwrap_err();
1522 languages
1523 .language_for_file("the/script", Some(&"nothing".into()))
1524 .await
1525 .unwrap_err();
1526 assert_eq!(
1527 languages
1528 .language_for_file("the/script", Some(&"#!/bin/env node".into()))
1529 .await
1530 .unwrap()
1531 .name()
1532 .as_ref(),
1533 "JavaScript"
1534 );
1535 }
1536
1537 #[gpui::test(iterations = 10)]
1538 async fn test_language_loading(cx: &mut TestAppContext) {
1539 let mut languages = LanguageRegistry::test();
1540 languages.set_executor(cx.executor());
1541 let languages = Arc::new(languages);
1542 languages.register_native_grammars([
1543 ("json", tree_sitter_json::language()),
1544 ("rust", tree_sitter_rust::language()),
1545 ]);
1546 languages.register_test_language(LanguageConfig {
1547 name: "JSON".into(),
1548 grammar: Some("json".into()),
1549 matcher: LanguageMatcher {
1550 path_suffixes: vec!["json".into()],
1551 ..Default::default()
1552 },
1553 ..Default::default()
1554 });
1555 languages.register_test_language(LanguageConfig {
1556 name: "Rust".into(),
1557 grammar: Some("rust".into()),
1558 matcher: LanguageMatcher {
1559 path_suffixes: vec!["rs".into()],
1560 ..Default::default()
1561 },
1562 ..Default::default()
1563 });
1564 assert_eq!(
1565 languages.language_names(),
1566 &[
1567 "JSON".to_string(),
1568 "Plain Text".to_string(),
1569 "Rust".to_string(),
1570 ]
1571 );
1572
1573 let rust1 = languages.language_for_name("Rust");
1574 let rust2 = languages.language_for_name("Rust");
1575
1576 // Ensure language is still listed even if it's being loaded.
1577 assert_eq!(
1578 languages.language_names(),
1579 &[
1580 "JSON".to_string(),
1581 "Plain Text".to_string(),
1582 "Rust".to_string(),
1583 ]
1584 );
1585
1586 let (rust1, rust2) = futures::join!(rust1, rust2);
1587 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1588
1589 // Ensure language is still listed even after loading it.
1590 assert_eq!(
1591 languages.language_names(),
1592 &[
1593 "JSON".to_string(),
1594 "Plain Text".to_string(),
1595 "Rust".to_string(),
1596 ]
1597 );
1598
1599 // Loading an unknown language returns an error.
1600 assert!(languages.language_for_name("Unknown").await.is_err());
1601 }
1602}