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