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
943 .grammar_mut()
944 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
945 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
946 Ok(self)
947 }
948
949 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
950 let grammar = self
951 .grammar_mut()
952 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
953 let query = Query::new(&grammar.ts_language, source)?;
954 let mut item_capture_ix = None;
955 let mut name_capture_ix = None;
956 let mut context_capture_ix = None;
957 let mut extra_context_capture_ix = None;
958 get_capture_indices(
959 &query,
960 &mut [
961 ("item", &mut item_capture_ix),
962 ("name", &mut name_capture_ix),
963 ("context", &mut context_capture_ix),
964 ("context.extra", &mut extra_context_capture_ix),
965 ],
966 );
967 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
968 grammar.outline_config = Some(OutlineConfig {
969 query,
970 item_capture_ix,
971 name_capture_ix,
972 context_capture_ix,
973 extra_context_capture_ix,
974 });
975 }
976 Ok(self)
977 }
978
979 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
980 let grammar = self
981 .grammar_mut()
982 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
983 let query = Query::new(&grammar.ts_language, source)?;
984 let mut item_capture_ix = None;
985 let mut name_capture_ix = None;
986 let mut context_capture_ix = None;
987 let mut collapse_capture_ix = None;
988 let mut keep_capture_ix = None;
989 get_capture_indices(
990 &query,
991 &mut [
992 ("item", &mut item_capture_ix),
993 ("name", &mut name_capture_ix),
994 ("context", &mut context_capture_ix),
995 ("keep", &mut keep_capture_ix),
996 ("collapse", &mut collapse_capture_ix),
997 ],
998 );
999 if let Some(item_capture_ix) = item_capture_ix {
1000 grammar.embedding_config = Some(EmbeddingConfig {
1001 query,
1002 item_capture_ix,
1003 name_capture_ix,
1004 context_capture_ix,
1005 collapse_capture_ix,
1006 keep_capture_ix,
1007 });
1008 }
1009 Ok(self)
1010 }
1011
1012 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1013 let grammar = self
1014 .grammar_mut()
1015 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1016 let query = Query::new(&grammar.ts_language, source)?;
1017 let mut open_capture_ix = None;
1018 let mut close_capture_ix = None;
1019 get_capture_indices(
1020 &query,
1021 &mut [
1022 ("open", &mut open_capture_ix),
1023 ("close", &mut close_capture_ix),
1024 ],
1025 );
1026 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1027 grammar.brackets_config = Some(BracketConfig {
1028 query,
1029 open_capture_ix,
1030 close_capture_ix,
1031 });
1032 }
1033 Ok(self)
1034 }
1035
1036 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1037 let grammar = self
1038 .grammar_mut()
1039 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1040 let query = Query::new(&grammar.ts_language, source)?;
1041 let mut indent_capture_ix = None;
1042 let mut start_capture_ix = None;
1043 let mut end_capture_ix = None;
1044 let mut outdent_capture_ix = None;
1045 get_capture_indices(
1046 &query,
1047 &mut [
1048 ("indent", &mut indent_capture_ix),
1049 ("start", &mut start_capture_ix),
1050 ("end", &mut end_capture_ix),
1051 ("outdent", &mut outdent_capture_ix),
1052 ],
1053 );
1054 if let Some(indent_capture_ix) = indent_capture_ix {
1055 grammar.indents_config = Some(IndentConfig {
1056 query,
1057 indent_capture_ix,
1058 start_capture_ix,
1059 end_capture_ix,
1060 outdent_capture_ix,
1061 });
1062 }
1063 Ok(self)
1064 }
1065
1066 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1067 let grammar = self
1068 .grammar_mut()
1069 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1070 let query = Query::new(&grammar.ts_language, source)?;
1071 let mut language_capture_ix = None;
1072 let mut content_capture_ix = None;
1073 get_capture_indices(
1074 &query,
1075 &mut [
1076 ("language", &mut language_capture_ix),
1077 ("content", &mut content_capture_ix),
1078 ],
1079 );
1080 let patterns = (0..query.pattern_count())
1081 .map(|ix| {
1082 let mut config = InjectionPatternConfig::default();
1083 for setting in query.property_settings(ix) {
1084 match setting.key.as_ref() {
1085 "language" => {
1086 config.language = setting.value.clone();
1087 }
1088 "combined" => {
1089 config.combined = true;
1090 }
1091 _ => {}
1092 }
1093 }
1094 config
1095 })
1096 .collect();
1097 if let Some(content_capture_ix) = content_capture_ix {
1098 grammar.injection_config = Some(InjectionConfig {
1099 query,
1100 language_capture_ix,
1101 content_capture_ix,
1102 patterns,
1103 });
1104 }
1105 Ok(self)
1106 }
1107
1108 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1109 let query = {
1110 let grammar = self
1111 .grammar
1112 .as_ref()
1113 .ok_or_else(|| anyhow!("no grammar for language"))?;
1114 Query::new(&grammar.ts_language, source)?
1115 };
1116
1117 let mut override_configs_by_id = HashMap::default();
1118 for (ix, name) in query.capture_names().iter().enumerate() {
1119 if !name.starts_with('_') {
1120 let value = self.config.overrides.remove(*name).unwrap_or_default();
1121 for server_name in &value.opt_into_language_servers {
1122 if !self
1123 .config
1124 .scope_opt_in_language_servers
1125 .contains(server_name)
1126 {
1127 util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1128 }
1129 }
1130
1131 override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1132 }
1133 }
1134
1135 if !self.config.overrides.is_empty() {
1136 let keys = self.config.overrides.keys().collect::<Vec<_>>();
1137 Err(anyhow!(
1138 "language {:?} has overrides in config not in query: {keys:?}",
1139 self.config.name
1140 ))?;
1141 }
1142
1143 for disabled_scope_name in self
1144 .config
1145 .brackets
1146 .disabled_scopes_by_bracket_ix
1147 .iter()
1148 .flatten()
1149 {
1150 if !override_configs_by_id
1151 .values()
1152 .any(|(scope_name, _)| scope_name == disabled_scope_name)
1153 {
1154 Err(anyhow!(
1155 "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1156 self.config.name
1157 ))?;
1158 }
1159 }
1160
1161 for (name, override_config) in override_configs_by_id.values_mut() {
1162 override_config.disabled_bracket_ixs = self
1163 .config
1164 .brackets
1165 .disabled_scopes_by_bracket_ix
1166 .iter()
1167 .enumerate()
1168 .filter_map(|(ix, disabled_scope_names)| {
1169 if disabled_scope_names.contains(name) {
1170 Some(ix as u16)
1171 } else {
1172 None
1173 }
1174 })
1175 .collect();
1176 }
1177
1178 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1179
1180 let grammar = self
1181 .grammar_mut()
1182 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1183 grammar.override_config = Some(OverrideConfig {
1184 query,
1185 values: override_configs_by_id,
1186 });
1187 Ok(self)
1188 }
1189
1190 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1191 let grammar = self
1192 .grammar_mut()
1193 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1194
1195 let query = Query::new(&grammar.ts_language, source)?;
1196 let mut redaction_capture_ix = None;
1197 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1198
1199 if let Some(redaction_capture_ix) = redaction_capture_ix {
1200 grammar.redactions_config = Some(RedactionConfig {
1201 query,
1202 redaction_capture_ix,
1203 });
1204 }
1205
1206 Ok(self)
1207 }
1208
1209 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1210 Arc::get_mut(self.grammar.as_mut()?)
1211 }
1212
1213 pub fn name(&self) -> Arc<str> {
1214 self.config.name.clone()
1215 }
1216
1217 pub fn context_provider(&self) -> Option<Arc<dyn LanguageContextProvider>> {
1218 self.context_provider.clone()
1219 }
1220
1221 pub fn highlight_text<'a>(
1222 self: &'a Arc<Self>,
1223 text: &'a Rope,
1224 range: Range<usize>,
1225 ) -> Vec<(Range<usize>, HighlightId)> {
1226 let mut result = Vec::new();
1227 if let Some(grammar) = &self.grammar {
1228 let tree = grammar.parse_text(text, None);
1229 let captures =
1230 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1231 grammar.highlights_query.as_ref()
1232 });
1233 let highlight_maps = vec![grammar.highlight_map()];
1234 let mut offset = 0;
1235 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1236 let end_offset = offset + chunk.text.len();
1237 if let Some(highlight_id) = chunk.syntax_highlight_id {
1238 if !highlight_id.is_default() {
1239 result.push((offset..end_offset, highlight_id));
1240 }
1241 }
1242 offset = end_offset;
1243 }
1244 }
1245 result
1246 }
1247
1248 pub fn path_suffixes(&self) -> &[String] {
1249 &self.config.matcher.path_suffixes
1250 }
1251
1252 pub fn should_autoclose_before(&self, c: char) -> bool {
1253 c.is_whitespace() || self.config.autoclose_before.contains(c)
1254 }
1255
1256 pub fn set_theme(&self, theme: &SyntaxTheme) {
1257 if let Some(grammar) = self.grammar.as_ref() {
1258 if let Some(highlights_query) = &grammar.highlights_query {
1259 *grammar.highlight_map.lock() =
1260 HighlightMap::new(highlights_query.capture_names(), theme);
1261 }
1262 }
1263 }
1264
1265 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1266 self.grammar.as_ref()
1267 }
1268
1269 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1270 LanguageScope {
1271 language: self.clone(),
1272 override_id: None,
1273 }
1274 }
1275
1276 pub fn prettier_parser_name(&self) -> Option<&str> {
1277 self.config.prettier_parser_name.as_deref()
1278 }
1279}
1280
1281impl LanguageScope {
1282 pub fn collapsed_placeholder(&self) -> &str {
1283 self.language.config.collapsed_placeholder.as_ref()
1284 }
1285
1286 /// Returns line prefix that is inserted in e.g. line continuations or
1287 /// in `toggle comments` action.
1288 pub fn line_comment_prefixes(&self) -> Option<&Vec<Arc<str>>> {
1289 Override::as_option(
1290 self.config_override().map(|o| &o.line_comments),
1291 Some(&self.language.config.line_comments),
1292 )
1293 }
1294
1295 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1296 Override::as_option(
1297 self.config_override().map(|o| &o.block_comment),
1298 self.language.config.block_comment.as_ref(),
1299 )
1300 .map(|e| (&e.0, &e.1))
1301 }
1302
1303 /// Returns a list of language-specific word characters.
1304 ///
1305 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1306 /// the purpose of actions like 'move to next word end` or whole-word search.
1307 /// It additionally accounts for language's additional word characters.
1308 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1309 Override::as_option(
1310 self.config_override().map(|o| &o.word_characters),
1311 Some(&self.language.config.word_characters),
1312 )
1313 }
1314
1315 /// Returns a list of bracket pairs for a given language with an additional
1316 /// piece of information about whether the particular bracket pair is currently active for a given language.
1317 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1318 let mut disabled_ids = self
1319 .config_override()
1320 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1321 self.language
1322 .config
1323 .brackets
1324 .pairs
1325 .iter()
1326 .enumerate()
1327 .map(move |(ix, bracket)| {
1328 let mut is_enabled = true;
1329 if let Some(next_disabled_ix) = disabled_ids.first() {
1330 if ix == *next_disabled_ix as usize {
1331 disabled_ids = &disabled_ids[1..];
1332 is_enabled = false;
1333 }
1334 }
1335 (bracket, is_enabled)
1336 })
1337 }
1338
1339 pub fn should_autoclose_before(&self, c: char) -> bool {
1340 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1341 }
1342
1343 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1344 let config = &self.language.config;
1345 let opt_in_servers = &config.scope_opt_in_language_servers;
1346 if opt_in_servers.iter().any(|o| *o == *name.0) {
1347 if let Some(over) = self.config_override() {
1348 over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1349 } else {
1350 false
1351 }
1352 } else {
1353 true
1354 }
1355 }
1356
1357 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1358 let id = self.override_id?;
1359 let grammar = self.language.grammar.as_ref()?;
1360 let override_config = grammar.override_config.as_ref()?;
1361 override_config.values.get(&id).map(|e| &e.1)
1362 }
1363}
1364
1365impl Hash for Language {
1366 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1367 self.id.hash(state)
1368 }
1369}
1370
1371impl PartialEq for Language {
1372 fn eq(&self, other: &Self) -> bool {
1373 self.id.eq(&other.id)
1374 }
1375}
1376
1377impl Eq for Language {}
1378
1379impl Debug for Language {
1380 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1381 f.debug_struct("Language")
1382 .field("name", &self.config.name)
1383 .finish()
1384 }
1385}
1386
1387impl Grammar {
1388 pub fn id(&self) -> GrammarId {
1389 self.id
1390 }
1391
1392 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1393 PARSER.with(|parser| {
1394 let mut parser = parser.borrow_mut();
1395 parser
1396 .set_language(&self.ts_language)
1397 .expect("incompatible grammar");
1398 let mut chunks = text.chunks_in_range(0..text.len());
1399 parser
1400 .parse_with(
1401 &mut move |offset, _| {
1402 chunks.seek(offset);
1403 chunks.next().unwrap_or("").as_bytes()
1404 },
1405 old_tree.as_ref(),
1406 )
1407 .unwrap()
1408 })
1409 }
1410
1411 pub fn highlight_map(&self) -> HighlightMap {
1412 self.highlight_map.lock().clone()
1413 }
1414
1415 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1416 let capture_id = self
1417 .highlights_query
1418 .as_ref()?
1419 .capture_index_for_name(name)?;
1420 Some(self.highlight_map.lock().get(capture_id))
1421 }
1422}
1423
1424impl CodeLabel {
1425 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1426 let mut result = Self {
1427 runs: Vec::new(),
1428 filter_range: 0..text.len(),
1429 text,
1430 };
1431 if let Some(filter_text) = filter_text {
1432 if let Some(ix) = result.text.find(filter_text) {
1433 result.filter_range = ix..ix + filter_text.len();
1434 }
1435 }
1436 result
1437 }
1438}
1439
1440impl Ord for LanguageMatcher {
1441 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1442 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1443 self.first_line_pattern
1444 .as_ref()
1445 .map(Regex::as_str)
1446 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1447 })
1448 }
1449}
1450
1451impl PartialOrd for LanguageMatcher {
1452 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1453 Some(self.cmp(other))
1454 }
1455}
1456
1457impl Eq for LanguageMatcher {}
1458
1459impl PartialEq for LanguageMatcher {
1460 fn eq(&self, other: &Self) -> bool {
1461 self.path_suffixes == other.path_suffixes
1462 && self.first_line_pattern.as_ref().map(Regex::as_str)
1463 == other.first_line_pattern.as_ref().map(Regex::as_str)
1464 }
1465}
1466
1467#[cfg(any(test, feature = "test-support"))]
1468impl Default for FakeLspAdapter {
1469 fn default() -> Self {
1470 Self {
1471 name: "the-fake-language-server",
1472 capabilities: lsp::LanguageServer::full_capabilities(),
1473 initializer: None,
1474 disk_based_diagnostics_progress_token: None,
1475 initialization_options: None,
1476 disk_based_diagnostics_sources: Vec::new(),
1477 prettier_plugins: Vec::new(),
1478 language_server_binary: LanguageServerBinary {
1479 path: "/the/fake/lsp/path".into(),
1480 arguments: vec![],
1481 env: Default::default(),
1482 },
1483 }
1484 }
1485}
1486
1487#[cfg(any(test, feature = "test-support"))]
1488#[async_trait]
1489impl LspAdapter for FakeLspAdapter {
1490 fn name(&self) -> LanguageServerName {
1491 LanguageServerName(self.name.into())
1492 }
1493
1494 fn get_language_server_command<'a>(
1495 self: Arc<Self>,
1496 _: Arc<Language>,
1497 _: Arc<Path>,
1498 _: Arc<dyn LspAdapterDelegate>,
1499 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1500 _: &'a mut AsyncAppContext,
1501 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1502 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1503 }
1504
1505 async fn fetch_latest_server_version(
1506 &self,
1507 _: &dyn LspAdapterDelegate,
1508 ) -> Result<Box<dyn 'static + Send + Any>> {
1509 unreachable!();
1510 }
1511
1512 async fn fetch_server_binary(
1513 &self,
1514 _: Box<dyn 'static + Send + Any>,
1515 _: PathBuf,
1516 _: &dyn LspAdapterDelegate,
1517 ) -> Result<LanguageServerBinary> {
1518 unreachable!();
1519 }
1520
1521 async fn cached_server_binary(
1522 &self,
1523 _: PathBuf,
1524 _: &dyn LspAdapterDelegate,
1525 ) -> Option<LanguageServerBinary> {
1526 unreachable!();
1527 }
1528
1529 async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1530 unreachable!();
1531 }
1532
1533 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1534
1535 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1536 self.disk_based_diagnostics_sources.clone()
1537 }
1538
1539 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1540 self.disk_based_diagnostics_progress_token.clone()
1541 }
1542
1543 fn initialization_options(&self) -> Option<Value> {
1544 self.initialization_options.clone()
1545 }
1546
1547 fn prettier_plugins(&self) -> &[&'static str] {
1548 &self.prettier_plugins
1549 }
1550
1551 fn as_fake(&self) -> Option<&FakeLspAdapter> {
1552 Some(self)
1553 }
1554}
1555
1556fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1557 for (ix, name) in query.capture_names().iter().enumerate() {
1558 for (capture_name, index) in captures.iter_mut() {
1559 if capture_name == name {
1560 **index = Some(ix as u32);
1561 break;
1562 }
1563 }
1564 }
1565}
1566
1567pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1568 lsp::Position::new(point.row, point.column)
1569}
1570
1571pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1572 Unclipped(PointUtf16::new(point.line, point.character))
1573}
1574
1575pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1576 lsp::Range {
1577 start: point_to_lsp(range.start),
1578 end: point_to_lsp(range.end),
1579 }
1580}
1581
1582pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1583 let mut start = point_from_lsp(range.start);
1584 let mut end = point_from_lsp(range.end);
1585 if start > end {
1586 mem::swap(&mut start, &mut end);
1587 }
1588 start..end
1589}
1590
1591#[cfg(test)]
1592mod tests {
1593 use super::*;
1594 use gpui::TestAppContext;
1595
1596 #[gpui::test(iterations = 10)]
1597 async fn test_first_line_pattern(cx: &mut TestAppContext) {
1598 let mut languages = LanguageRegistry::test();
1599
1600 languages.set_executor(cx.executor());
1601 let languages = Arc::new(languages);
1602 languages.register_test_language(LanguageConfig {
1603 name: "JavaScript".into(),
1604 matcher: LanguageMatcher {
1605 path_suffixes: vec!["js".into()],
1606 first_line_pattern: Some(Regex::new(r"\bnode\b").unwrap()),
1607 },
1608 ..Default::default()
1609 });
1610
1611 languages
1612 .language_for_file("the/script".as_ref(), None)
1613 .await
1614 .unwrap_err();
1615 languages
1616 .language_for_file("the/script".as_ref(), Some(&"nothing".into()))
1617 .await
1618 .unwrap_err();
1619 assert_eq!(
1620 languages
1621 .language_for_file("the/script".as_ref(), Some(&"#!/bin/env node".into()))
1622 .await
1623 .unwrap()
1624 .name()
1625 .as_ref(),
1626 "JavaScript"
1627 );
1628 }
1629
1630 #[gpui::test(iterations = 10)]
1631 async fn test_language_loading(cx: &mut TestAppContext) {
1632 let mut languages = LanguageRegistry::test();
1633 languages.set_executor(cx.executor());
1634 let languages = Arc::new(languages);
1635 languages.register_native_grammars([
1636 ("json", tree_sitter_json::language()),
1637 ("rust", tree_sitter_rust::language()),
1638 ]);
1639 languages.register_test_language(LanguageConfig {
1640 name: "JSON".into(),
1641 grammar: Some("json".into()),
1642 matcher: LanguageMatcher {
1643 path_suffixes: vec!["json".into()],
1644 ..Default::default()
1645 },
1646 ..Default::default()
1647 });
1648 languages.register_test_language(LanguageConfig {
1649 name: "Rust".into(),
1650 grammar: Some("rust".into()),
1651 matcher: LanguageMatcher {
1652 path_suffixes: vec!["rs".into()],
1653 ..Default::default()
1654 },
1655 ..Default::default()
1656 });
1657 assert_eq!(
1658 languages.language_names(),
1659 &[
1660 "JSON".to_string(),
1661 "Plain Text".to_string(),
1662 "Rust".to_string(),
1663 ]
1664 );
1665
1666 let rust1 = languages.language_for_name("Rust");
1667 let rust2 = languages.language_for_name("Rust");
1668
1669 // Ensure language is still listed even if it's being loaded.
1670 assert_eq!(
1671 languages.language_names(),
1672 &[
1673 "JSON".to_string(),
1674 "Plain Text".to_string(),
1675 "Rust".to_string(),
1676 ]
1677 );
1678
1679 let (rust1, rust2) = futures::join!(rust1, rust2);
1680 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1681
1682 // Ensure language is still listed even after loading it.
1683 assert_eq!(
1684 languages.language_names(),
1685 &[
1686 "JSON".to_string(),
1687 "Plain Text".to_string(),
1688 "Rust".to_string(),
1689 ]
1690 );
1691
1692 // Loading an unknown language returns an error.
1693 assert!(languages.language_for_name("Unknown").await.is_err());
1694 }
1695}