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