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 manifest;
15mod outline;
16pub mod proto;
17mod syntax_map;
18mod task_context;
19mod text_diff;
20mod toolchain;
21
22#[cfg(test)]
23pub mod buffer_tests;
24
25pub use crate::language_settings::EditPredictionsMode;
26use crate::language_settings::SoftWrap;
27use anyhow::{Context as _, Result};
28use async_trait::async_trait;
29use collections::{HashMap, HashSet, IndexSet};
30use fs::Fs;
31use futures::Future;
32use gpui::{App, AsyncApp, Entity, SharedString, Task};
33pub use highlight_map::HighlightMap;
34use http_client::HttpClient;
35pub use language_registry::{
36 LanguageName, LanguageServerStatusUpdate, LoadedLanguage, ServerHealth,
37};
38use lsp::{CodeActionKind, InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions};
39pub use manifest::{ManifestDelegate, ManifestName, ManifestProvider, ManifestQuery};
40use parking_lot::Mutex;
41use regex::Regex;
42use schemars::{JsonSchema, json_schema};
43use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
44use serde_json::Value;
45use settings::WorktreeId;
46use smol::future::FutureExt as _;
47use std::{
48 any::Any,
49 ffi::OsStr,
50 fmt::Debug,
51 hash::Hash,
52 mem,
53 ops::{DerefMut, Range},
54 path::{Path, PathBuf},
55 pin::Pin,
56 str,
57 sync::{
58 Arc, LazyLock,
59 atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
60 },
61};
62use std::{num::NonZeroU32, sync::OnceLock};
63use syntax_map::{QueryCursorHandle, SyntaxSnapshot};
64use task::RunnableTag;
65pub use task_context::{ContextLocation, ContextProvider, RunnableRange};
66pub use text_diff::{
67 DiffOptions, apply_diff_patch, line_diff, text_diff, text_diff_with_options, unified_diff,
68};
69use theme::SyntaxTheme;
70pub use toolchain::{LanguageToolchainStore, Toolchain, ToolchainList, ToolchainLister};
71use tree_sitter::{self, Query, QueryCursor, WasmStore, wasmtime};
72use util::serde::default_true;
73
74pub use buffer::Operation;
75pub use buffer::*;
76pub use diagnostic_set::{DiagnosticEntry, DiagnosticGroup};
77pub use language_registry::{
78 AvailableLanguage, BinaryStatus, LanguageNotFound, LanguageQueries, LanguageRegistry,
79 QUERY_FILENAME_PREFIXES,
80};
81pub use lsp::{LanguageServerId, LanguageServerName};
82pub use outline::*;
83pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer, ToTreeSitterPoint, TreeSitterOptions};
84pub use text::{AnchorRangeExt, LineEnding};
85pub use tree_sitter::{Node, Parser, Tree, TreeCursor};
86
87/// Initializes the `language` crate.
88///
89/// This should be called before making use of items from the create.
90pub fn init(cx: &mut App) {
91 language_settings::init(cx);
92}
93
94static QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Mutex::new(vec![]);
95static PARSERS: Mutex<Vec<Parser>> = Mutex::new(vec![]);
96
97pub fn with_parser<F, R>(func: F) -> R
98where
99 F: FnOnce(&mut Parser) -> R,
100{
101 let mut parser = PARSERS.lock().pop().unwrap_or_else(|| {
102 let mut parser = Parser::new();
103 parser
104 .set_wasm_store(WasmStore::new(&WASM_ENGINE).unwrap())
105 .unwrap();
106 parser
107 });
108 parser.set_included_ranges(&[]).unwrap();
109 let result = func(&mut parser);
110 PARSERS.lock().push(parser);
111 result
112}
113
114pub fn with_query_cursor<F, R>(func: F) -> R
115where
116 F: FnOnce(&mut QueryCursor) -> R,
117{
118 let mut cursor = QueryCursorHandle::new();
119 func(cursor.deref_mut())
120}
121
122static NEXT_LANGUAGE_ID: LazyLock<AtomicUsize> = LazyLock::new(Default::default);
123static NEXT_GRAMMAR_ID: LazyLock<AtomicUsize> = LazyLock::new(Default::default);
124static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
125 wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
126});
127
128/// A shared grammar for plain text, exposed for reuse by downstream crates.
129pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
130 Arc::new(Language::new(
131 LanguageConfig {
132 name: "Plain Text".into(),
133 soft_wrap: Some(SoftWrap::EditorWidth),
134 matcher: LanguageMatcher {
135 path_suffixes: vec!["txt".to_owned()],
136 first_line_pattern: None,
137 },
138 ..Default::default()
139 },
140 None,
141 ))
142});
143
144/// Types that represent a position in a buffer, and can be converted into
145/// an LSP position, to send to a language server.
146pub trait ToLspPosition {
147 /// Converts the value into an LSP position.
148 fn to_lsp_position(self) -> lsp::Position;
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Hash)]
152pub struct Location {
153 pub buffer: Entity<Buffer>,
154 pub range: Range<Anchor>,
155}
156
157/// Represents a Language Server, with certain cached sync properties.
158/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
159/// once at startup, and caches the results.
160pub struct CachedLspAdapter {
161 pub name: LanguageServerName,
162 pub disk_based_diagnostic_sources: Vec<String>,
163 pub disk_based_diagnostics_progress_token: Option<String>,
164 language_ids: HashMap<String, String>,
165 pub adapter: Arc<dyn LspAdapter>,
166 pub reinstall_attempt_count: AtomicU64,
167 cached_binary: futures::lock::Mutex<Option<LanguageServerBinary>>,
168 manifest_name: OnceLock<Option<ManifestName>>,
169 attach_kind: OnceLock<Attach>,
170}
171
172impl Debug for CachedLspAdapter {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 f.debug_struct("CachedLspAdapter")
175 .field("name", &self.name)
176 .field(
177 "disk_based_diagnostic_sources",
178 &self.disk_based_diagnostic_sources,
179 )
180 .field(
181 "disk_based_diagnostics_progress_token",
182 &self.disk_based_diagnostics_progress_token,
183 )
184 .field("language_ids", &self.language_ids)
185 .field("reinstall_attempt_count", &self.reinstall_attempt_count)
186 .finish_non_exhaustive()
187 }
188}
189
190impl CachedLspAdapter {
191 pub fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
192 let name = adapter.name();
193 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
194 let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
195 let language_ids = adapter.language_ids();
196
197 Arc::new(CachedLspAdapter {
198 name,
199 disk_based_diagnostic_sources,
200 disk_based_diagnostics_progress_token,
201 language_ids,
202 adapter,
203 cached_binary: Default::default(),
204 reinstall_attempt_count: AtomicU64::new(0),
205 attach_kind: Default::default(),
206 manifest_name: Default::default(),
207 })
208 }
209
210 pub fn name(&self) -> LanguageServerName {
211 self.adapter.name().clone()
212 }
213
214 pub async fn get_language_server_command(
215 self: Arc<Self>,
216 delegate: Arc<dyn LspAdapterDelegate>,
217 toolchains: Arc<dyn LanguageToolchainStore>,
218 binary_options: LanguageServerBinaryOptions,
219 cx: &mut AsyncApp,
220 ) -> Result<LanguageServerBinary> {
221 let cached_binary = self.cached_binary.lock().await;
222 self.adapter
223 .clone()
224 .get_language_server_command(delegate, toolchains, binary_options, cached_binary, cx)
225 .await
226 }
227
228 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
229 self.adapter.code_action_kinds()
230 }
231
232 pub fn process_diagnostics(
233 &self,
234 params: &mut lsp::PublishDiagnosticsParams,
235 server_id: LanguageServerId,
236 existing_diagnostics: Option<&'_ Buffer>,
237 ) {
238 self.adapter
239 .process_diagnostics(params, server_id, existing_diagnostics)
240 }
241
242 pub fn retain_old_diagnostic(&self, previous_diagnostic: &Diagnostic, cx: &App) -> bool {
243 self.adapter.retain_old_diagnostic(previous_diagnostic, cx)
244 }
245
246 pub fn underline_diagnostic(&self, diagnostic: &lsp::Diagnostic) -> bool {
247 self.adapter.underline_diagnostic(diagnostic)
248 }
249
250 pub fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
251 self.adapter.diagnostic_message_to_markdown(message)
252 }
253
254 pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
255 self.adapter.process_completions(completion_items).await
256 }
257
258 pub async fn labels_for_completions(
259 &self,
260 completion_items: &[lsp::CompletionItem],
261 language: &Arc<Language>,
262 ) -> Result<Vec<Option<CodeLabel>>> {
263 self.adapter
264 .clone()
265 .labels_for_completions(completion_items, language)
266 .await
267 }
268
269 pub async fn labels_for_symbols(
270 &self,
271 symbols: &[(String, lsp::SymbolKind)],
272 language: &Arc<Language>,
273 ) -> Result<Vec<Option<CodeLabel>>> {
274 self.adapter
275 .clone()
276 .labels_for_symbols(symbols, language)
277 .await
278 }
279
280 pub fn language_id(&self, language_name: &LanguageName) -> String {
281 self.language_ids
282 .get(language_name.as_ref())
283 .cloned()
284 .unwrap_or_else(|| language_name.lsp_id())
285 }
286 pub fn manifest_name(&self) -> Option<ManifestName> {
287 self.manifest_name
288 .get_or_init(|| self.adapter.manifest_name())
289 .clone()
290 }
291 pub fn attach_kind(&self) -> Attach {
292 *self.attach_kind.get_or_init(|| self.adapter.attach_kind())
293 }
294}
295
296#[derive(Clone, Copy, Debug, PartialEq)]
297pub enum Attach {
298 /// Create a single language server instance per subproject root.
299 InstancePerRoot,
300 /// Use one shared language server instance for all subprojects within a project.
301 Shared,
302}
303
304impl Attach {
305 pub fn root_path(
306 &self,
307 root_subproject_path: (WorktreeId, Arc<Path>),
308 ) -> (WorktreeId, Arc<Path>) {
309 match self {
310 Attach::InstancePerRoot => root_subproject_path,
311 Attach::Shared => (root_subproject_path.0, Arc::from(Path::new(""))),
312 }
313 }
314}
315
316/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
317// e.g. to display a notification or fetch data from the web.
318#[async_trait]
319pub trait LspAdapterDelegate: Send + Sync {
320 fn show_notification(&self, message: &str, cx: &mut App);
321 fn http_client(&self) -> Arc<dyn HttpClient>;
322 fn worktree_id(&self) -> WorktreeId;
323 fn worktree_root_path(&self) -> &Path;
324 fn update_status(&self, language: LanguageServerName, status: BinaryStatus);
325 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>>;
326 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>>;
327
328 async fn npm_package_installed_version(
329 &self,
330 package_name: &str,
331 ) -> Result<Option<(PathBuf, String)>>;
332 async fn which(&self, command: &OsStr) -> Option<PathBuf>;
333 async fn shell_env(&self) -> HashMap<String, String>;
334 async fn read_text_file(&self, path: PathBuf) -> Result<String>;
335 async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
336}
337
338#[async_trait(?Send)]
339pub trait LspAdapter: 'static + Send + Sync {
340 fn name(&self) -> LanguageServerName;
341
342 fn get_language_server_command<'a>(
343 self: Arc<Self>,
344 delegate: Arc<dyn LspAdapterDelegate>,
345 toolchains: Arc<dyn LanguageToolchainStore>,
346 binary_options: LanguageServerBinaryOptions,
347 mut cached_binary: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
348 cx: &'a mut AsyncApp,
349 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
350 async move {
351 // First we check whether the adapter can give us a user-installed binary.
352 // If so, we do *not* want to cache that, because each worktree might give us a different
353 // binary:
354 //
355 // worktree 1: user-installed at `.bin/gopls`
356 // worktree 2: user-installed at `~/bin/gopls`
357 // worktree 3: no gopls found in PATH -> fallback to Zed installation
358 //
359 // We only want to cache when we fall back to the global one,
360 // because we don't want to download and overwrite our global one
361 // for each worktree we might have open.
362 if binary_options.allow_path_lookup {
363 if let Some(binary) = self.check_if_user_installed(delegate.as_ref(), toolchains, cx).await {
364 log::info!(
365 "found user-installed language server for {}. path: {:?}, arguments: {:?}",
366 self.name().0,
367 binary.path,
368 binary.arguments
369 );
370 return Ok(binary);
371 }
372 }
373
374 anyhow::ensure!(binary_options.allow_binary_download, "downloading language servers disabled");
375
376 if let Some(cached_binary) = cached_binary.as_ref() {
377 return Ok(cached_binary.clone());
378 }
379
380 let Some(container_dir) = delegate.language_server_download_dir(&self.name()).await else {
381 anyhow::bail!("no language server download dir defined")
382 };
383
384 let mut binary = try_fetch_server_binary(self.as_ref(), &delegate, container_dir.to_path_buf(), cx).await;
385
386 if let Err(error) = binary.as_ref() {
387 if let Some(prev_downloaded_binary) = self
388 .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
389 .await
390 {
391 log::info!(
392 "failed to fetch newest version of language server {:?}. error: {:?}, falling back to using {:?}",
393 self.name(),
394 error,
395 prev_downloaded_binary.path
396 );
397 binary = Ok(prev_downloaded_binary);
398 } else {
399 delegate.update_status(
400 self.name(),
401 BinaryStatus::Failed {
402 error: format!("{error:?}"),
403 },
404 );
405 }
406 }
407
408 if let Ok(binary) = &binary {
409 *cached_binary = Some(binary.clone());
410 }
411
412 binary
413 }
414 .boxed_local()
415 }
416
417 async fn check_if_user_installed(
418 &self,
419 _: &dyn LspAdapterDelegate,
420 _: Arc<dyn LanguageToolchainStore>,
421 _: &AsyncApp,
422 ) -> Option<LanguageServerBinary> {
423 None
424 }
425
426 async fn fetch_latest_server_version(
427 &self,
428 delegate: &dyn LspAdapterDelegate,
429 ) -> Result<Box<dyn 'static + Send + Any>>;
430
431 fn will_fetch_server(
432 &self,
433 _: &Arc<dyn LspAdapterDelegate>,
434 _: &mut AsyncApp,
435 ) -> Option<Task<Result<()>>> {
436 None
437 }
438
439 async fn check_if_version_installed(
440 &self,
441 _version: &(dyn 'static + Send + Any),
442 _container_dir: &PathBuf,
443 _delegate: &dyn LspAdapterDelegate,
444 ) -> Option<LanguageServerBinary> {
445 None
446 }
447
448 async fn fetch_server_binary(
449 &self,
450 latest_version: Box<dyn 'static + Send + Any>,
451 container_dir: PathBuf,
452 delegate: &dyn LspAdapterDelegate,
453 ) -> Result<LanguageServerBinary>;
454
455 async fn cached_server_binary(
456 &self,
457 container_dir: PathBuf,
458 delegate: &dyn LspAdapterDelegate,
459 ) -> Option<LanguageServerBinary>;
460
461 fn process_diagnostics(
462 &self,
463 _: &mut lsp::PublishDiagnosticsParams,
464 _: LanguageServerId,
465 _: Option<&'_ Buffer>,
466 ) {
467 }
468
469 /// When processing new `lsp::PublishDiagnosticsParams` diagnostics, whether to retain previous one(s) or not.
470 fn retain_old_diagnostic(&self, _previous_diagnostic: &Diagnostic, _cx: &App) -> bool {
471 false
472 }
473
474 /// Whether to underline a given diagnostic or not, when rendering in the editor.
475 ///
476 /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnosticTag
477 /// states that
478 /// > Clients are allowed to render diagnostics with this tag faded out instead of having an error squiggle.
479 /// for the unnecessary diagnostics, so do not underline them.
480 fn underline_diagnostic(&self, _diagnostic: &lsp::Diagnostic) -> bool {
481 true
482 }
483
484 /// Post-processes completions provided by the language server.
485 async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
486
487 fn diagnostic_message_to_markdown(&self, _message: &str) -> Option<String> {
488 None
489 }
490
491 async fn labels_for_completions(
492 self: Arc<Self>,
493 completions: &[lsp::CompletionItem],
494 language: &Arc<Language>,
495 ) -> Result<Vec<Option<CodeLabel>>> {
496 let mut labels = Vec::new();
497 for (ix, completion) in completions.iter().enumerate() {
498 let label = self.label_for_completion(completion, language).await;
499 if let Some(label) = label {
500 labels.resize(ix + 1, None);
501 *labels.last_mut().unwrap() = Some(label);
502 }
503 }
504 Ok(labels)
505 }
506
507 async fn label_for_completion(
508 &self,
509 _: &lsp::CompletionItem,
510 _: &Arc<Language>,
511 ) -> Option<CodeLabel> {
512 None
513 }
514
515 async fn labels_for_symbols(
516 self: Arc<Self>,
517 symbols: &[(String, lsp::SymbolKind)],
518 language: &Arc<Language>,
519 ) -> Result<Vec<Option<CodeLabel>>> {
520 let mut labels = Vec::new();
521 for (ix, (name, kind)) in symbols.iter().enumerate() {
522 let label = self.label_for_symbol(name, *kind, language).await;
523 if let Some(label) = label {
524 labels.resize(ix + 1, None);
525 *labels.last_mut().unwrap() = Some(label);
526 }
527 }
528 Ok(labels)
529 }
530
531 async fn label_for_symbol(
532 &self,
533 _: &str,
534 _: lsp::SymbolKind,
535 _: &Arc<Language>,
536 ) -> Option<CodeLabel> {
537 None
538 }
539
540 /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
541 async fn initialization_options(
542 self: Arc<Self>,
543 _: &dyn Fs,
544 _: &Arc<dyn LspAdapterDelegate>,
545 ) -> Result<Option<Value>> {
546 Ok(None)
547 }
548
549 async fn workspace_configuration(
550 self: Arc<Self>,
551 _: &dyn Fs,
552 _: &Arc<dyn LspAdapterDelegate>,
553 _: Arc<dyn LanguageToolchainStore>,
554 _cx: &mut AsyncApp,
555 ) -> Result<Value> {
556 Ok(serde_json::json!({}))
557 }
558
559 async fn additional_initialization_options(
560 self: Arc<Self>,
561 _target_language_server_id: LanguageServerName,
562 _: &dyn Fs,
563 _: &Arc<dyn LspAdapterDelegate>,
564 ) -> Result<Option<Value>> {
565 Ok(None)
566 }
567
568 async fn additional_workspace_configuration(
569 self: Arc<Self>,
570 _target_language_server_id: LanguageServerName,
571 _: &dyn Fs,
572 _: &Arc<dyn LspAdapterDelegate>,
573 _: Arc<dyn LanguageToolchainStore>,
574 _cx: &mut AsyncApp,
575 ) -> Result<Option<Value>> {
576 Ok(None)
577 }
578
579 /// Returns a list of code actions supported by a given LspAdapter
580 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
581 None
582 }
583
584 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
585 Default::default()
586 }
587
588 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
589 None
590 }
591
592 fn language_ids(&self) -> HashMap<String, String> {
593 Default::default()
594 }
595
596 /// Support custom initialize params.
597 fn prepare_initialize_params(
598 &self,
599 original: InitializeParams,
600 _: &App,
601 ) -> Result<InitializeParams> {
602 Ok(original)
603 }
604
605 fn attach_kind(&self) -> Attach {
606 Attach::Shared
607 }
608
609 fn manifest_name(&self) -> Option<ManifestName> {
610 None
611 }
612
613 /// Method only implemented by the default JSON language server adapter.
614 /// Used to provide dynamic reloading of the JSON schemas used to
615 /// provide autocompletion and diagnostics in Zed setting and keybind
616 /// files
617 fn is_primary_zed_json_schema_adapter(&self) -> bool {
618 false
619 }
620
621 /// Method only implemented by the default JSON language server adapter.
622 /// Used to clear the cache of JSON schemas that are used to provide
623 /// autocompletion and diagnostics in Zed settings and keybinds files.
624 /// Should not be called unless the callee is sure that
625 /// `Self::is_primary_zed_json_schema_adapter` returns `true`
626 async fn clear_zed_json_schema_cache(&self) {
627 unreachable!(
628 "Not implemented for this adapter. This method should only be called on the default JSON language server adapter"
629 );
630 }
631}
632
633async fn try_fetch_server_binary<L: LspAdapter + 'static + Send + Sync + ?Sized>(
634 adapter: &L,
635 delegate: &Arc<dyn LspAdapterDelegate>,
636 container_dir: PathBuf,
637 cx: &mut AsyncApp,
638) -> Result<LanguageServerBinary> {
639 if let Some(task) = adapter.will_fetch_server(delegate, cx) {
640 task.await?;
641 }
642
643 let name = adapter.name();
644 log::info!("fetching latest version of language server {:?}", name.0);
645 delegate.update_status(name.clone(), BinaryStatus::CheckingForUpdate);
646
647 let latest_version = adapter
648 .fetch_latest_server_version(delegate.as_ref())
649 .await?;
650
651 if let Some(binary) = adapter
652 .check_if_version_installed(latest_version.as_ref(), &container_dir, delegate.as_ref())
653 .await
654 {
655 log::info!("language server {:?} is already installed", name.0);
656 delegate.update_status(name.clone(), BinaryStatus::None);
657 Ok(binary)
658 } else {
659 log::info!("downloading language server {:?}", name.0);
660 delegate.update_status(adapter.name(), BinaryStatus::Downloading);
661 let binary = adapter
662 .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
663 .await;
664
665 delegate.update_status(name.clone(), BinaryStatus::None);
666 binary
667 }
668}
669
670#[derive(Clone, Debug, Default, PartialEq, Eq)]
671pub struct CodeLabel {
672 /// The text to display.
673 pub text: String,
674 /// Syntax highlighting runs.
675 pub runs: Vec<(Range<usize>, HighlightId)>,
676 /// The portion of the text that should be used in fuzzy filtering.
677 pub filter_range: Range<usize>,
678}
679
680#[derive(Clone, Deserialize, JsonSchema)]
681pub struct LanguageConfig {
682 /// Human-readable name of the language.
683 pub name: LanguageName,
684 /// The name of this language for a Markdown code fence block
685 pub code_fence_block_name: Option<Arc<str>>,
686 // The name of the grammar in a WASM bundle (experimental).
687 pub grammar: Option<Arc<str>>,
688 /// The criteria for matching this language to a given file.
689 #[serde(flatten)]
690 pub matcher: LanguageMatcher,
691 /// List of bracket types in a language.
692 #[serde(default)]
693 pub brackets: BracketPairConfig,
694 /// If set to true, auto indentation uses last non empty line to determine
695 /// the indentation level for a new line.
696 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
697 pub auto_indent_using_last_non_empty_line: bool,
698 // Whether indentation of pasted content should be adjusted based on the context.
699 #[serde(default)]
700 pub auto_indent_on_paste: Option<bool>,
701 /// A regex that is used to determine whether the indentation level should be
702 /// increased in the following line.
703 #[serde(default, deserialize_with = "deserialize_regex")]
704 #[schemars(schema_with = "regex_json_schema")]
705 pub increase_indent_pattern: Option<Regex>,
706 /// A regex that is used to determine whether the indentation level should be
707 /// decreased in the following line.
708 #[serde(default, deserialize_with = "deserialize_regex")]
709 #[schemars(schema_with = "regex_json_schema")]
710 pub decrease_indent_pattern: Option<Regex>,
711 /// A list of rules for decreasing indentation. Each rule pairs a regex with a set of valid
712 /// "block-starting" tokens. When a line matches a pattern, its indentation is aligned with
713 /// the most recent line that began with a corresponding token. This enables context-aware
714 /// outdenting, like aligning an `else` with its `if`.
715 #[serde(default)]
716 pub decrease_indent_patterns: Vec<DecreaseIndentConfig>,
717 /// A list of characters that trigger the automatic insertion of a closing
718 /// bracket when they immediately precede the point where an opening
719 /// bracket is inserted.
720 #[serde(default)]
721 pub autoclose_before: String,
722 /// A placeholder used internally by Semantic Index.
723 #[serde(default)]
724 pub collapsed_placeholder: String,
725 /// A line comment string that is inserted in e.g. `toggle comments` action.
726 /// A language can have multiple flavours of line comments. All of the provided line comments are
727 /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
728 #[serde(default)]
729 pub line_comments: Vec<Arc<str>>,
730 /// Starting and closing characters of a block comment.
731 #[serde(default)]
732 pub block_comment: Option<(Arc<str>, Arc<str>)>,
733 /// A list of language servers that are allowed to run on subranges of a given language.
734 #[serde(default)]
735 pub scope_opt_in_language_servers: Vec<LanguageServerName>,
736 #[serde(default)]
737 pub overrides: HashMap<String, LanguageConfigOverride>,
738 /// A list of characters that Zed should treat as word characters for the
739 /// purpose of features that operate on word boundaries, like 'move to next word end'
740 /// or a whole-word search in buffer search.
741 #[serde(default)]
742 pub word_characters: HashSet<char>,
743 /// Whether to indent lines using tab characters, as opposed to multiple
744 /// spaces.
745 #[serde(default)]
746 pub hard_tabs: Option<bool>,
747 /// How many columns a tab should occupy.
748 #[serde(default)]
749 pub tab_size: Option<NonZeroU32>,
750 /// How to soft-wrap long lines of text.
751 #[serde(default)]
752 pub soft_wrap: Option<SoftWrap>,
753 /// The name of a Prettier parser that will be used for this language when no file path is available.
754 /// If there's a parser name in the language settings, that will be used instead.
755 #[serde(default)]
756 pub prettier_parser_name: Option<String>,
757 /// If true, this language is only for syntax highlighting via an injection into other
758 /// languages, but should not appear to the user as a distinct language.
759 #[serde(default)]
760 pub hidden: bool,
761 /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
762 #[serde(default)]
763 pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
764 /// A list of characters that Zed should treat as word characters for completion queries.
765 #[serde(default)]
766 pub completion_query_characters: HashSet<char>,
767 /// A list of preferred debuggers for this language.
768 #[serde(default)]
769 pub debuggers: IndexSet<SharedString>,
770 /// Whether to treat documentation comment of this language differently by
771 /// auto adding prefix on new line, adjusting the indenting , etc.
772 #[serde(default)]
773 pub documentation: Option<DocumentationConfig>,
774}
775
776#[derive(Clone, Debug, Deserialize, Default, JsonSchema)]
777pub struct DecreaseIndentConfig {
778 #[serde(default, deserialize_with = "deserialize_regex")]
779 #[schemars(schema_with = "regex_json_schema")]
780 pub pattern: Option<Regex>,
781 #[serde(default)]
782 pub valid_after: Vec<String>,
783}
784
785#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
786pub struct LanguageMatcher {
787 /// 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`.
788 #[serde(default)]
789 pub path_suffixes: Vec<String>,
790 /// A regex pattern that determines whether the language should be assigned to a file or not.
791 #[serde(
792 default,
793 serialize_with = "serialize_regex",
794 deserialize_with = "deserialize_regex"
795 )]
796 #[schemars(schema_with = "regex_json_schema")]
797 pub first_line_pattern: Option<Regex>,
798}
799
800/// The configuration for JSX tag auto-closing.
801#[derive(Clone, Deserialize, JsonSchema)]
802pub struct JsxTagAutoCloseConfig {
803 /// The name of the node for a opening tag
804 pub open_tag_node_name: String,
805 /// The name of the node for an closing tag
806 pub close_tag_node_name: String,
807 /// The name of the node for a complete element with children for open and close tags
808 pub jsx_element_node_name: String,
809 /// The name of the node found within both opening and closing
810 /// tags that describes the tag name
811 pub tag_name_node_name: String,
812 /// Alternate Node names for tag names.
813 /// Specifically needed as TSX represents the name in `<Foo.Bar>`
814 /// as `member_expression` rather than `identifier` as usual
815 #[serde(default)]
816 pub tag_name_node_name_alternates: Vec<String>,
817 /// Some grammars are smart enough to detect a closing tag
818 /// that is not valid i.e. doesn't match it's corresponding
819 /// opening tag or does not have a corresponding opening tag
820 /// This should be set to the name of the node for invalid
821 /// closing tags if the grammar contains such a node, otherwise
822 /// detecting already closed tags will not work properly
823 #[serde(default)]
824 pub erroneous_close_tag_node_name: Option<String>,
825 /// See above for erroneous_close_tag_node_name for details
826 /// This should be set if the node used for the tag name
827 /// within erroneous closing tags is different from the
828 /// normal tag name node name
829 #[serde(default)]
830 pub erroneous_close_tag_name_node_name: Option<String>,
831}
832
833/// The configuration for documentation block for this language.
834#[derive(Clone, Deserialize, JsonSchema)]
835pub struct DocumentationConfig {
836 /// A start tag of documentation block.
837 pub start: Arc<str>,
838 /// A end tag of documentation block.
839 pub end: Arc<str>,
840 /// A character to add as a prefix when a new line is added to a documentation block.
841 pub prefix: Arc<str>,
842 /// A indent to add for prefix and end line upon new line.
843 pub tab_size: NonZeroU32,
844}
845
846/// Represents a language for the given range. Some languages (e.g. HTML)
847/// interleave several languages together, thus a single buffer might actually contain
848/// several nested scopes.
849#[derive(Clone, Debug)]
850pub struct LanguageScope {
851 language: Arc<Language>,
852 override_id: Option<u32>,
853}
854
855#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
856pub struct LanguageConfigOverride {
857 #[serde(default)]
858 pub line_comments: Override<Vec<Arc<str>>>,
859 #[serde(default)]
860 pub block_comment: Override<(Arc<str>, Arc<str>)>,
861 #[serde(skip)]
862 pub disabled_bracket_ixs: Vec<u16>,
863 #[serde(default)]
864 pub word_characters: Override<HashSet<char>>,
865 #[serde(default)]
866 pub completion_query_characters: Override<HashSet<char>>,
867 #[serde(default)]
868 pub opt_into_language_servers: Vec<LanguageServerName>,
869 #[serde(default)]
870 pub prefer_label_for_snippet: Option<bool>,
871}
872
873#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
874#[serde(untagged)]
875pub enum Override<T> {
876 Remove { remove: bool },
877 Set(T),
878}
879
880impl<T> Default for Override<T> {
881 fn default() -> Self {
882 Override::Remove { remove: false }
883 }
884}
885
886impl<T> Override<T> {
887 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
888 match this {
889 Some(Self::Set(value)) => Some(value),
890 Some(Self::Remove { remove: true }) => None,
891 Some(Self::Remove { remove: false }) | None => original,
892 }
893 }
894}
895
896impl Default for LanguageConfig {
897 fn default() -> Self {
898 Self {
899 name: LanguageName::new(""),
900 code_fence_block_name: None,
901 grammar: None,
902 matcher: LanguageMatcher::default(),
903 brackets: Default::default(),
904 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
905 auto_indent_on_paste: None,
906 increase_indent_pattern: Default::default(),
907 decrease_indent_pattern: Default::default(),
908 decrease_indent_patterns: Default::default(),
909 autoclose_before: Default::default(),
910 line_comments: Default::default(),
911 block_comment: Default::default(),
912 scope_opt_in_language_servers: Default::default(),
913 overrides: Default::default(),
914 word_characters: Default::default(),
915 collapsed_placeholder: Default::default(),
916 hard_tabs: None,
917 tab_size: None,
918 soft_wrap: None,
919 prettier_parser_name: None,
920 hidden: false,
921 jsx_tag_auto_close: None,
922 completion_query_characters: Default::default(),
923 debuggers: Default::default(),
924 documentation: None,
925 }
926 }
927}
928
929fn auto_indent_using_last_non_empty_line_default() -> bool {
930 true
931}
932
933fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
934 let source = Option::<String>::deserialize(d)?;
935 if let Some(source) = source {
936 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
937 } else {
938 Ok(None)
939 }
940}
941
942fn regex_json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
943 json_schema!({
944 "type": "string"
945 })
946}
947
948fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
949where
950 S: Serializer,
951{
952 match regex {
953 Some(regex) => serializer.serialize_str(regex.as_str()),
954 None => serializer.serialize_none(),
955 }
956}
957
958#[doc(hidden)]
959#[cfg(any(test, feature = "test-support"))]
960pub struct FakeLspAdapter {
961 pub name: &'static str,
962 pub initialization_options: Option<Value>,
963 pub prettier_plugins: Vec<&'static str>,
964 pub disk_based_diagnostics_progress_token: Option<String>,
965 pub disk_based_diagnostics_sources: Vec<String>,
966 pub language_server_binary: LanguageServerBinary,
967
968 pub capabilities: lsp::ServerCapabilities,
969 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
970 pub label_for_completion: Option<
971 Box<
972 dyn 'static
973 + Send
974 + Sync
975 + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
976 >,
977 >,
978}
979
980/// Configuration of handling bracket pairs for a given language.
981///
982/// This struct includes settings for defining which pairs of characters are considered brackets and
983/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
984#[derive(Clone, Debug, Default, JsonSchema)]
985#[schemars(with = "Vec::<BracketPairContent>")]
986pub struct BracketPairConfig {
987 /// A list of character pairs that should be treated as brackets in the context of a given language.
988 pub pairs: Vec<BracketPair>,
989 /// A list of tree-sitter scopes for which a given bracket should not be active.
990 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
991 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
992}
993
994impl BracketPairConfig {
995 pub fn is_closing_brace(&self, c: char) -> bool {
996 self.pairs.iter().any(|pair| pair.end.starts_with(c))
997 }
998}
999
1000#[derive(Deserialize, JsonSchema)]
1001pub struct BracketPairContent {
1002 #[serde(flatten)]
1003 pub bracket_pair: BracketPair,
1004 #[serde(default)]
1005 pub not_in: Vec<String>,
1006}
1007
1008impl<'de> Deserialize<'de> for BracketPairConfig {
1009 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1010 where
1011 D: Deserializer<'de>,
1012 {
1013 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
1014 let mut brackets = Vec::with_capacity(result.len());
1015 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
1016 for entry in result {
1017 brackets.push(entry.bracket_pair);
1018 disabled_scopes_by_bracket_ix.push(entry.not_in);
1019 }
1020
1021 Ok(BracketPairConfig {
1022 pairs: brackets,
1023 disabled_scopes_by_bracket_ix,
1024 })
1025 }
1026}
1027
1028/// Describes a single bracket pair and how an editor should react to e.g. inserting
1029/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
1030#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
1031pub struct BracketPair {
1032 /// Starting substring for a bracket.
1033 pub start: String,
1034 /// Ending substring for a bracket.
1035 pub end: String,
1036 /// True if `end` should be automatically inserted right after `start` characters.
1037 pub close: bool,
1038 /// True if selected text should be surrounded by `start` and `end` characters.
1039 #[serde(default = "default_true")]
1040 pub surround: bool,
1041 /// True if an extra newline should be inserted while the cursor is in the middle
1042 /// of that bracket pair.
1043 pub newline: bool,
1044}
1045
1046#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1047pub struct LanguageId(usize);
1048
1049impl LanguageId {
1050 pub(crate) fn new() -> Self {
1051 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
1052 }
1053}
1054
1055pub struct Language {
1056 pub(crate) id: LanguageId,
1057 pub(crate) config: LanguageConfig,
1058 pub(crate) grammar: Option<Arc<Grammar>>,
1059 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1060 pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1061}
1062
1063#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1064pub struct GrammarId(pub usize);
1065
1066impl GrammarId {
1067 pub(crate) fn new() -> Self {
1068 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1069 }
1070}
1071
1072pub struct Grammar {
1073 id: GrammarId,
1074 pub ts_language: tree_sitter::Language,
1075 pub(crate) error_query: Option<Query>,
1076 pub(crate) highlights_query: Option<Query>,
1077 pub(crate) brackets_config: Option<BracketsConfig>,
1078 pub(crate) redactions_config: Option<RedactionConfig>,
1079 pub(crate) runnable_config: Option<RunnableConfig>,
1080 pub(crate) indents_config: Option<IndentConfig>,
1081 pub outline_config: Option<OutlineConfig>,
1082 pub text_object_config: Option<TextObjectConfig>,
1083 pub embedding_config: Option<EmbeddingConfig>,
1084 pub(crate) injection_config: Option<InjectionConfig>,
1085 pub(crate) override_config: Option<OverrideConfig>,
1086 pub(crate) debug_variables_config: Option<DebugVariablesConfig>,
1087 pub(crate) highlight_map: Mutex<HighlightMap>,
1088}
1089
1090struct IndentConfig {
1091 query: Query,
1092 indent_capture_ix: u32,
1093 start_capture_ix: Option<u32>,
1094 end_capture_ix: Option<u32>,
1095 outdent_capture_ix: Option<u32>,
1096 suffixed_start_captures: HashMap<u32, SharedString>,
1097}
1098
1099pub struct OutlineConfig {
1100 pub query: Query,
1101 pub item_capture_ix: u32,
1102 pub name_capture_ix: u32,
1103 pub context_capture_ix: Option<u32>,
1104 pub extra_context_capture_ix: Option<u32>,
1105 pub open_capture_ix: Option<u32>,
1106 pub close_capture_ix: Option<u32>,
1107 pub annotation_capture_ix: Option<u32>,
1108}
1109
1110#[derive(Debug, Clone, Copy, PartialEq)]
1111pub enum DebuggerTextObject {
1112 Variable,
1113 Scope,
1114}
1115
1116impl DebuggerTextObject {
1117 pub fn from_capture_name(name: &str) -> Option<DebuggerTextObject> {
1118 match name {
1119 "debug-variable" => Some(DebuggerTextObject::Variable),
1120 "debug-scope" => Some(DebuggerTextObject::Scope),
1121 _ => None,
1122 }
1123 }
1124}
1125
1126#[derive(Debug, Clone, Copy, PartialEq)]
1127pub enum TextObject {
1128 InsideFunction,
1129 AroundFunction,
1130 InsideClass,
1131 AroundClass,
1132 InsideComment,
1133 AroundComment,
1134}
1135
1136impl TextObject {
1137 pub fn from_capture_name(name: &str) -> Option<TextObject> {
1138 match name {
1139 "function.inside" => Some(TextObject::InsideFunction),
1140 "function.around" => Some(TextObject::AroundFunction),
1141 "class.inside" => Some(TextObject::InsideClass),
1142 "class.around" => Some(TextObject::AroundClass),
1143 "comment.inside" => Some(TextObject::InsideComment),
1144 "comment.around" => Some(TextObject::AroundComment),
1145 _ => None,
1146 }
1147 }
1148
1149 pub fn around(&self) -> Option<Self> {
1150 match self {
1151 TextObject::InsideFunction => Some(TextObject::AroundFunction),
1152 TextObject::InsideClass => Some(TextObject::AroundClass),
1153 TextObject::InsideComment => Some(TextObject::AroundComment),
1154 _ => None,
1155 }
1156 }
1157}
1158
1159pub struct TextObjectConfig {
1160 pub query: Query,
1161 pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1162}
1163
1164#[derive(Debug)]
1165pub struct EmbeddingConfig {
1166 pub query: Query,
1167 pub item_capture_ix: u32,
1168 pub name_capture_ix: Option<u32>,
1169 pub context_capture_ix: Option<u32>,
1170 pub collapse_capture_ix: Option<u32>,
1171 pub keep_capture_ix: Option<u32>,
1172}
1173
1174struct InjectionConfig {
1175 query: Query,
1176 content_capture_ix: u32,
1177 language_capture_ix: Option<u32>,
1178 patterns: Vec<InjectionPatternConfig>,
1179}
1180
1181struct RedactionConfig {
1182 pub query: Query,
1183 pub redaction_capture_ix: u32,
1184}
1185
1186#[derive(Clone, Debug, PartialEq)]
1187enum RunnableCapture {
1188 Named(SharedString),
1189 Run,
1190}
1191
1192struct RunnableConfig {
1193 pub query: Query,
1194 /// A mapping from capture indice to capture kind
1195 pub extra_captures: Vec<RunnableCapture>,
1196}
1197
1198struct OverrideConfig {
1199 query: Query,
1200 values: HashMap<u32, OverrideEntry>,
1201}
1202
1203#[derive(Debug)]
1204struct OverrideEntry {
1205 name: String,
1206 range_is_inclusive: bool,
1207 value: LanguageConfigOverride,
1208}
1209
1210#[derive(Default, Clone)]
1211struct InjectionPatternConfig {
1212 language: Option<Box<str>>,
1213 combined: bool,
1214}
1215
1216struct BracketsConfig {
1217 query: Query,
1218 open_capture_ix: u32,
1219 close_capture_ix: u32,
1220 patterns: Vec<BracketsPatternConfig>,
1221}
1222
1223#[derive(Clone, Debug, Default)]
1224struct BracketsPatternConfig {
1225 newline_only: bool,
1226}
1227
1228pub struct DebugVariablesConfig {
1229 pub query: Query,
1230 pub objects_by_capture_ix: Vec<(u32, DebuggerTextObject)>,
1231}
1232
1233impl Language {
1234 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1235 Self::new_with_id(LanguageId::new(), config, ts_language)
1236 }
1237
1238 pub fn id(&self) -> LanguageId {
1239 self.id
1240 }
1241
1242 fn new_with_id(
1243 id: LanguageId,
1244 config: LanguageConfig,
1245 ts_language: Option<tree_sitter::Language>,
1246 ) -> Self {
1247 Self {
1248 id,
1249 config,
1250 grammar: ts_language.map(|ts_language| {
1251 Arc::new(Grammar {
1252 id: GrammarId::new(),
1253 highlights_query: None,
1254 brackets_config: None,
1255 outline_config: None,
1256 text_object_config: None,
1257 embedding_config: None,
1258 indents_config: None,
1259 injection_config: None,
1260 override_config: None,
1261 redactions_config: None,
1262 runnable_config: None,
1263 error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1264 debug_variables_config: None,
1265 ts_language,
1266 highlight_map: Default::default(),
1267 })
1268 }),
1269 context_provider: None,
1270 toolchain: None,
1271 }
1272 }
1273
1274 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1275 self.context_provider = provider;
1276 self
1277 }
1278
1279 pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1280 self.toolchain = provider;
1281 self
1282 }
1283
1284 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1285 if let Some(query) = queries.highlights {
1286 self = self
1287 .with_highlights_query(query.as_ref())
1288 .context("Error loading highlights query")?;
1289 }
1290 if let Some(query) = queries.brackets {
1291 self = self
1292 .with_brackets_query(query.as_ref())
1293 .context("Error loading brackets query")?;
1294 }
1295 if let Some(query) = queries.indents {
1296 self = self
1297 .with_indents_query(query.as_ref())
1298 .context("Error loading indents query")?;
1299 }
1300 if let Some(query) = queries.outline {
1301 self = self
1302 .with_outline_query(query.as_ref())
1303 .context("Error loading outline query")?;
1304 }
1305 if let Some(query) = queries.embedding {
1306 self = self
1307 .with_embedding_query(query.as_ref())
1308 .context("Error loading embedding query")?;
1309 }
1310 if let Some(query) = queries.injections {
1311 self = self
1312 .with_injection_query(query.as_ref())
1313 .context("Error loading injection query")?;
1314 }
1315 if let Some(query) = queries.overrides {
1316 self = self
1317 .with_override_query(query.as_ref())
1318 .context("Error loading override query")?;
1319 }
1320 if let Some(query) = queries.redactions {
1321 self = self
1322 .with_redaction_query(query.as_ref())
1323 .context("Error loading redaction query")?;
1324 }
1325 if let Some(query) = queries.runnables {
1326 self = self
1327 .with_runnable_query(query.as_ref())
1328 .context("Error loading runnables query")?;
1329 }
1330 if let Some(query) = queries.text_objects {
1331 self = self
1332 .with_text_object_query(query.as_ref())
1333 .context("Error loading textobject query")?;
1334 }
1335 if let Some(query) = queries.debugger {
1336 self = self
1337 .with_debug_variables_query(query.as_ref())
1338 .context("Error loading debug variables query")?;
1339 }
1340 Ok(self)
1341 }
1342
1343 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1344 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1345 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1346 Ok(self)
1347 }
1348
1349 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1350 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1351
1352 let query = Query::new(&grammar.ts_language, source)?;
1353 let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1354
1355 for name in query.capture_names().iter() {
1356 let kind = if *name == "run" {
1357 RunnableCapture::Run
1358 } else {
1359 RunnableCapture::Named(name.to_string().into())
1360 };
1361 extra_captures.push(kind);
1362 }
1363
1364 grammar.runnable_config = Some(RunnableConfig {
1365 extra_captures,
1366 query,
1367 });
1368
1369 Ok(self)
1370 }
1371
1372 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1373 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1374 let query = Query::new(&grammar.ts_language, source)?;
1375 let mut item_capture_ix = None;
1376 let mut name_capture_ix = None;
1377 let mut context_capture_ix = None;
1378 let mut extra_context_capture_ix = None;
1379 let mut open_capture_ix = None;
1380 let mut close_capture_ix = None;
1381 let mut annotation_capture_ix = None;
1382 get_capture_indices(
1383 &query,
1384 &mut [
1385 ("item", &mut item_capture_ix),
1386 ("name", &mut name_capture_ix),
1387 ("context", &mut context_capture_ix),
1388 ("context.extra", &mut extra_context_capture_ix),
1389 ("open", &mut open_capture_ix),
1390 ("close", &mut close_capture_ix),
1391 ("annotation", &mut annotation_capture_ix),
1392 ],
1393 );
1394 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1395 grammar.outline_config = Some(OutlineConfig {
1396 query,
1397 item_capture_ix,
1398 name_capture_ix,
1399 context_capture_ix,
1400 extra_context_capture_ix,
1401 open_capture_ix,
1402 close_capture_ix,
1403 annotation_capture_ix,
1404 });
1405 }
1406 Ok(self)
1407 }
1408
1409 pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1410 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1411 let query = Query::new(&grammar.ts_language, source)?;
1412
1413 let mut text_objects_by_capture_ix = Vec::new();
1414 for (ix, name) in query.capture_names().iter().enumerate() {
1415 if let Some(text_object) = TextObject::from_capture_name(name) {
1416 text_objects_by_capture_ix.push((ix as u32, text_object));
1417 }
1418 }
1419
1420 grammar.text_object_config = Some(TextObjectConfig {
1421 query,
1422 text_objects_by_capture_ix,
1423 });
1424 Ok(self)
1425 }
1426
1427 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1428 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1429 let query = Query::new(&grammar.ts_language, source)?;
1430 let mut item_capture_ix = None;
1431 let mut name_capture_ix = None;
1432 let mut context_capture_ix = None;
1433 let mut collapse_capture_ix = None;
1434 let mut keep_capture_ix = None;
1435 get_capture_indices(
1436 &query,
1437 &mut [
1438 ("item", &mut item_capture_ix),
1439 ("name", &mut name_capture_ix),
1440 ("context", &mut context_capture_ix),
1441 ("keep", &mut keep_capture_ix),
1442 ("collapse", &mut collapse_capture_ix),
1443 ],
1444 );
1445 if let Some(item_capture_ix) = item_capture_ix {
1446 grammar.embedding_config = Some(EmbeddingConfig {
1447 query,
1448 item_capture_ix,
1449 name_capture_ix,
1450 context_capture_ix,
1451 collapse_capture_ix,
1452 keep_capture_ix,
1453 });
1454 }
1455 Ok(self)
1456 }
1457
1458 pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1459 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1460 let query = Query::new(&grammar.ts_language, source)?;
1461
1462 let mut objects_by_capture_ix = Vec::new();
1463 for (ix, name) in query.capture_names().iter().enumerate() {
1464 if let Some(text_object) = DebuggerTextObject::from_capture_name(name) {
1465 objects_by_capture_ix.push((ix as u32, text_object));
1466 }
1467 }
1468
1469 grammar.debug_variables_config = Some(DebugVariablesConfig {
1470 query,
1471 objects_by_capture_ix,
1472 });
1473 Ok(self)
1474 }
1475
1476 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1477 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1478 let query = Query::new(&grammar.ts_language, source)?;
1479 let mut open_capture_ix = None;
1480 let mut close_capture_ix = None;
1481 get_capture_indices(
1482 &query,
1483 &mut [
1484 ("open", &mut open_capture_ix),
1485 ("close", &mut close_capture_ix),
1486 ],
1487 );
1488 let patterns = (0..query.pattern_count())
1489 .map(|ix| {
1490 let mut config = BracketsPatternConfig::default();
1491 for setting in query.property_settings(ix) {
1492 match setting.key.as_ref() {
1493 "newline.only" => config.newline_only = true,
1494 _ => {}
1495 }
1496 }
1497 config
1498 })
1499 .collect();
1500 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1501 grammar.brackets_config = Some(BracketsConfig {
1502 query,
1503 open_capture_ix,
1504 close_capture_ix,
1505 patterns,
1506 });
1507 }
1508 Ok(self)
1509 }
1510
1511 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1512 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1513 let query = Query::new(&grammar.ts_language, source)?;
1514 let mut indent_capture_ix = None;
1515 let mut start_capture_ix = None;
1516 let mut end_capture_ix = None;
1517 let mut outdent_capture_ix = None;
1518 get_capture_indices(
1519 &query,
1520 &mut [
1521 ("indent", &mut indent_capture_ix),
1522 ("start", &mut start_capture_ix),
1523 ("end", &mut end_capture_ix),
1524 ("outdent", &mut outdent_capture_ix),
1525 ],
1526 );
1527
1528 let mut suffixed_start_captures = HashMap::default();
1529 for (ix, name) in query.capture_names().iter().enumerate() {
1530 if let Some(suffix) = name.strip_prefix("start.") {
1531 suffixed_start_captures.insert(ix as u32, suffix.to_owned().into());
1532 }
1533 }
1534
1535 if let Some(indent_capture_ix) = indent_capture_ix {
1536 grammar.indents_config = Some(IndentConfig {
1537 query,
1538 indent_capture_ix,
1539 start_capture_ix,
1540 end_capture_ix,
1541 outdent_capture_ix,
1542 suffixed_start_captures,
1543 });
1544 }
1545 Ok(self)
1546 }
1547
1548 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1549 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1550 let query = Query::new(&grammar.ts_language, source)?;
1551 let mut language_capture_ix = None;
1552 let mut injection_language_capture_ix = None;
1553 let mut content_capture_ix = None;
1554 let mut injection_content_capture_ix = None;
1555 get_capture_indices(
1556 &query,
1557 &mut [
1558 ("language", &mut language_capture_ix),
1559 ("injection.language", &mut injection_language_capture_ix),
1560 ("content", &mut content_capture_ix),
1561 ("injection.content", &mut injection_content_capture_ix),
1562 ],
1563 );
1564 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1565 (None, Some(ix)) => Some(ix),
1566 (Some(_), Some(_)) => {
1567 anyhow::bail!("both language and injection.language captures are present");
1568 }
1569 _ => language_capture_ix,
1570 };
1571 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1572 (None, Some(ix)) => Some(ix),
1573 (Some(_), Some(_)) => {
1574 anyhow::bail!("both content and injection.content captures are present")
1575 }
1576 _ => content_capture_ix,
1577 };
1578 let patterns = (0..query.pattern_count())
1579 .map(|ix| {
1580 let mut config = InjectionPatternConfig::default();
1581 for setting in query.property_settings(ix) {
1582 match setting.key.as_ref() {
1583 "language" | "injection.language" => {
1584 config.language.clone_from(&setting.value);
1585 }
1586 "combined" | "injection.combined" => {
1587 config.combined = true;
1588 }
1589 _ => {}
1590 }
1591 }
1592 config
1593 })
1594 .collect();
1595 if let Some(content_capture_ix) = content_capture_ix {
1596 grammar.injection_config = Some(InjectionConfig {
1597 query,
1598 language_capture_ix,
1599 content_capture_ix,
1600 patterns,
1601 });
1602 }
1603 Ok(self)
1604 }
1605
1606 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1607 let query = {
1608 let grammar = self.grammar.as_ref().context("no grammar for language")?;
1609 Query::new(&grammar.ts_language, source)?
1610 };
1611
1612 let mut override_configs_by_id = HashMap::default();
1613 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1614 let mut range_is_inclusive = false;
1615 if name.starts_with('_') {
1616 continue;
1617 }
1618 if let Some(prefix) = name.strip_suffix(".inclusive") {
1619 name = prefix;
1620 range_is_inclusive = true;
1621 }
1622
1623 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1624 for server_name in &value.opt_into_language_servers {
1625 if !self
1626 .config
1627 .scope_opt_in_language_servers
1628 .contains(server_name)
1629 {
1630 util::debug_panic!(
1631 "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1632 );
1633 }
1634 }
1635
1636 override_configs_by_id.insert(
1637 ix as u32,
1638 OverrideEntry {
1639 name: name.to_string(),
1640 range_is_inclusive,
1641 value,
1642 },
1643 );
1644 }
1645
1646 let referenced_override_names = self.config.overrides.keys().chain(
1647 self.config
1648 .brackets
1649 .disabled_scopes_by_bracket_ix
1650 .iter()
1651 .flatten(),
1652 );
1653
1654 for referenced_name in referenced_override_names {
1655 if !override_configs_by_id
1656 .values()
1657 .any(|entry| entry.name == *referenced_name)
1658 {
1659 anyhow::bail!(
1660 "language {:?} has overrides in config not in query: {referenced_name:?}",
1661 self.config.name
1662 );
1663 }
1664 }
1665
1666 for entry in override_configs_by_id.values_mut() {
1667 entry.value.disabled_bracket_ixs = self
1668 .config
1669 .brackets
1670 .disabled_scopes_by_bracket_ix
1671 .iter()
1672 .enumerate()
1673 .filter_map(|(ix, disabled_scope_names)| {
1674 if disabled_scope_names.contains(&entry.name) {
1675 Some(ix as u16)
1676 } else {
1677 None
1678 }
1679 })
1680 .collect();
1681 }
1682
1683 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1684
1685 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1686 grammar.override_config = Some(OverrideConfig {
1687 query,
1688 values: override_configs_by_id,
1689 });
1690 Ok(self)
1691 }
1692
1693 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1694 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1695
1696 let query = Query::new(&grammar.ts_language, source)?;
1697 let mut redaction_capture_ix = None;
1698 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1699
1700 if let Some(redaction_capture_ix) = redaction_capture_ix {
1701 grammar.redactions_config = Some(RedactionConfig {
1702 query,
1703 redaction_capture_ix,
1704 });
1705 }
1706
1707 Ok(self)
1708 }
1709
1710 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1711 Arc::get_mut(self.grammar.as_mut()?)
1712 }
1713
1714 pub fn name(&self) -> LanguageName {
1715 self.config.name.clone()
1716 }
1717
1718 pub fn code_fence_block_name(&self) -> Arc<str> {
1719 self.config
1720 .code_fence_block_name
1721 .clone()
1722 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1723 }
1724
1725 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1726 self.context_provider.clone()
1727 }
1728
1729 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1730 self.toolchain.clone()
1731 }
1732
1733 pub fn highlight_text<'a>(
1734 self: &'a Arc<Self>,
1735 text: &'a Rope,
1736 range: Range<usize>,
1737 ) -> Vec<(Range<usize>, HighlightId)> {
1738 let mut result = Vec::new();
1739 if let Some(grammar) = &self.grammar {
1740 let tree = grammar.parse_text(text, None);
1741 let captures =
1742 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1743 grammar.highlights_query.as_ref()
1744 });
1745 let highlight_maps = vec![grammar.highlight_map()];
1746 let mut offset = 0;
1747 for chunk in
1748 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1749 {
1750 let end_offset = offset + chunk.text.len();
1751 if let Some(highlight_id) = chunk.syntax_highlight_id {
1752 if !highlight_id.is_default() {
1753 result.push((offset..end_offset, highlight_id));
1754 }
1755 }
1756 offset = end_offset;
1757 }
1758 }
1759 result
1760 }
1761
1762 pub fn path_suffixes(&self) -> &[String] {
1763 &self.config.matcher.path_suffixes
1764 }
1765
1766 pub fn should_autoclose_before(&self, c: char) -> bool {
1767 c.is_whitespace() || self.config.autoclose_before.contains(c)
1768 }
1769
1770 pub fn set_theme(&self, theme: &SyntaxTheme) {
1771 if let Some(grammar) = self.grammar.as_ref() {
1772 if let Some(highlights_query) = &grammar.highlights_query {
1773 *grammar.highlight_map.lock() =
1774 HighlightMap::new(highlights_query.capture_names(), theme);
1775 }
1776 }
1777 }
1778
1779 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1780 self.grammar.as_ref()
1781 }
1782
1783 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1784 LanguageScope {
1785 language: self.clone(),
1786 override_id: None,
1787 }
1788 }
1789
1790 pub fn lsp_id(&self) -> String {
1791 self.config.name.lsp_id()
1792 }
1793
1794 pub fn prettier_parser_name(&self) -> Option<&str> {
1795 self.config.prettier_parser_name.as_deref()
1796 }
1797
1798 pub fn config(&self) -> &LanguageConfig {
1799 &self.config
1800 }
1801}
1802
1803impl LanguageScope {
1804 pub fn path_suffixes(&self) -> &[String] {
1805 &self.language.path_suffixes()
1806 }
1807
1808 pub fn language_name(&self) -> LanguageName {
1809 self.language.config.name.clone()
1810 }
1811
1812 pub fn collapsed_placeholder(&self) -> &str {
1813 self.language.config.collapsed_placeholder.as_ref()
1814 }
1815
1816 /// Returns line prefix that is inserted in e.g. line continuations or
1817 /// in `toggle comments` action.
1818 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1819 Override::as_option(
1820 self.config_override().map(|o| &o.line_comments),
1821 Some(&self.language.config.line_comments),
1822 )
1823 .map_or([].as_slice(), |e| e.as_slice())
1824 }
1825
1826 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1827 Override::as_option(
1828 self.config_override().map(|o| &o.block_comment),
1829 self.language.config.block_comment.as_ref(),
1830 )
1831 .map(|e| (&e.0, &e.1))
1832 }
1833
1834 /// Returns a list of language-specific word characters.
1835 ///
1836 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1837 /// the purpose of actions like 'move to next word end` or whole-word search.
1838 /// It additionally accounts for language's additional word characters.
1839 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1840 Override::as_option(
1841 self.config_override().map(|o| &o.word_characters),
1842 Some(&self.language.config.word_characters),
1843 )
1844 }
1845
1846 /// Returns a list of language-specific characters that are considered part of
1847 /// a completion query.
1848 pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1849 Override::as_option(
1850 self.config_override()
1851 .map(|o| &o.completion_query_characters),
1852 Some(&self.language.config.completion_query_characters),
1853 )
1854 }
1855
1856 /// Returns whether to prefer snippet `label` over `new_text` to replace text when
1857 /// completion is accepted.
1858 ///
1859 /// In cases like when cursor is in string or renaming existing function,
1860 /// you don't want to expand function signature instead just want function name
1861 /// to replace existing one.
1862 pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
1863 self.config_override()
1864 .and_then(|o| o.prefer_label_for_snippet)
1865 .unwrap_or(false)
1866 }
1867
1868 /// Returns config to documentation block for this language.
1869 ///
1870 /// Used for documentation styles that require a leading character on each line,
1871 /// such as the asterisk in JSDoc, Javadoc, etc.
1872 pub fn documentation(&self) -> Option<&DocumentationConfig> {
1873 self.language.config.documentation.as_ref()
1874 }
1875
1876 /// Returns a list of bracket pairs for a given language with an additional
1877 /// piece of information about whether the particular bracket pair is currently active for a given language.
1878 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1879 let mut disabled_ids = self
1880 .config_override()
1881 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1882 self.language
1883 .config
1884 .brackets
1885 .pairs
1886 .iter()
1887 .enumerate()
1888 .map(move |(ix, bracket)| {
1889 let mut is_enabled = true;
1890 if let Some(next_disabled_ix) = disabled_ids.first() {
1891 if ix == *next_disabled_ix as usize {
1892 disabled_ids = &disabled_ids[1..];
1893 is_enabled = false;
1894 }
1895 }
1896 (bracket, is_enabled)
1897 })
1898 }
1899
1900 pub fn should_autoclose_before(&self, c: char) -> bool {
1901 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1902 }
1903
1904 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1905 let config = &self.language.config;
1906 let opt_in_servers = &config.scope_opt_in_language_servers;
1907 if opt_in_servers.contains(name) {
1908 if let Some(over) = self.config_override() {
1909 over.opt_into_language_servers.contains(name)
1910 } else {
1911 false
1912 }
1913 } else {
1914 true
1915 }
1916 }
1917
1918 pub fn override_name(&self) -> Option<&str> {
1919 let id = self.override_id?;
1920 let grammar = self.language.grammar.as_ref()?;
1921 let override_config = grammar.override_config.as_ref()?;
1922 override_config.values.get(&id).map(|e| e.name.as_str())
1923 }
1924
1925 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1926 let id = self.override_id?;
1927 let grammar = self.language.grammar.as_ref()?;
1928 let override_config = grammar.override_config.as_ref()?;
1929 override_config.values.get(&id).map(|e| &e.value)
1930 }
1931}
1932
1933impl Hash for Language {
1934 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1935 self.id.hash(state)
1936 }
1937}
1938
1939impl PartialEq for Language {
1940 fn eq(&self, other: &Self) -> bool {
1941 self.id.eq(&other.id)
1942 }
1943}
1944
1945impl Eq for Language {}
1946
1947impl Debug for Language {
1948 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1949 f.debug_struct("Language")
1950 .field("name", &self.config.name)
1951 .finish()
1952 }
1953}
1954
1955impl Grammar {
1956 pub fn id(&self) -> GrammarId {
1957 self.id
1958 }
1959
1960 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1961 with_parser(|parser| {
1962 parser
1963 .set_language(&self.ts_language)
1964 .expect("incompatible grammar");
1965 let mut chunks = text.chunks_in_range(0..text.len());
1966 parser
1967 .parse_with_options(
1968 &mut move |offset, _| {
1969 chunks.seek(offset);
1970 chunks.next().unwrap_or("").as_bytes()
1971 },
1972 old_tree.as_ref(),
1973 None,
1974 )
1975 .unwrap()
1976 })
1977 }
1978
1979 pub fn highlight_map(&self) -> HighlightMap {
1980 self.highlight_map.lock().clone()
1981 }
1982
1983 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1984 let capture_id = self
1985 .highlights_query
1986 .as_ref()?
1987 .capture_index_for_name(name)?;
1988 Some(self.highlight_map.lock().get(capture_id))
1989 }
1990
1991 pub fn debug_variables_config(&self) -> Option<&DebugVariablesConfig> {
1992 self.debug_variables_config.as_ref()
1993 }
1994}
1995
1996impl CodeLabel {
1997 pub fn fallback_for_completion(
1998 item: &lsp::CompletionItem,
1999 language: Option<&Language>,
2000 ) -> Self {
2001 let highlight_id = item.kind.and_then(|kind| {
2002 let grammar = language?.grammar()?;
2003 use lsp::CompletionItemKind as Kind;
2004 match kind {
2005 Kind::CLASS => grammar.highlight_id_for_name("type"),
2006 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
2007 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
2008 Kind::ENUM => grammar
2009 .highlight_id_for_name("enum")
2010 .or_else(|| grammar.highlight_id_for_name("type")),
2011 Kind::ENUM_MEMBER => grammar
2012 .highlight_id_for_name("variant")
2013 .or_else(|| grammar.highlight_id_for_name("property")),
2014 Kind::FIELD => grammar.highlight_id_for_name("property"),
2015 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
2016 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
2017 Kind::METHOD => grammar
2018 .highlight_id_for_name("function.method")
2019 .or_else(|| grammar.highlight_id_for_name("function")),
2020 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
2021 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
2022 Kind::STRUCT => grammar.highlight_id_for_name("type"),
2023 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
2024 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
2025 _ => None,
2026 }
2027 });
2028
2029 let label = &item.label;
2030 let label_length = label.len();
2031 let runs = highlight_id
2032 .map(|highlight_id| vec![(0..label_length, highlight_id)])
2033 .unwrap_or_default();
2034 let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
2035 format!("{label} {detail}")
2036 } else if let Some(description) = item
2037 .label_details
2038 .as_ref()
2039 .and_then(|label_details| label_details.description.as_deref())
2040 .filter(|description| description != label)
2041 {
2042 format!("{label} {description}")
2043 } else {
2044 label.clone()
2045 };
2046 let filter_range = item
2047 .filter_text
2048 .as_deref()
2049 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2050 .unwrap_or(0..label_length);
2051 Self {
2052 text,
2053 runs,
2054 filter_range,
2055 }
2056 }
2057
2058 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
2059 let filter_range = filter_text
2060 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2061 .unwrap_or(0..text.len());
2062 Self {
2063 runs: Vec::new(),
2064 filter_range,
2065 text,
2066 }
2067 }
2068
2069 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2070 let start_ix = self.text.len();
2071 self.text.push_str(text);
2072 let end_ix = self.text.len();
2073 if let Some(highlight) = highlight {
2074 self.runs.push((start_ix..end_ix, highlight));
2075 }
2076 }
2077
2078 pub fn text(&self) -> &str {
2079 self.text.as_str()
2080 }
2081
2082 pub fn filter_text(&self) -> &str {
2083 &self.text[self.filter_range.clone()]
2084 }
2085}
2086
2087impl From<String> for CodeLabel {
2088 fn from(value: String) -> Self {
2089 Self::plain(value, None)
2090 }
2091}
2092
2093impl From<&str> for CodeLabel {
2094 fn from(value: &str) -> Self {
2095 Self::plain(value.to_string(), None)
2096 }
2097}
2098
2099impl Ord for LanguageMatcher {
2100 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2101 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2102 self.first_line_pattern
2103 .as_ref()
2104 .map(Regex::as_str)
2105 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2106 })
2107 }
2108}
2109
2110impl PartialOrd for LanguageMatcher {
2111 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2112 Some(self.cmp(other))
2113 }
2114}
2115
2116impl Eq for LanguageMatcher {}
2117
2118impl PartialEq for LanguageMatcher {
2119 fn eq(&self, other: &Self) -> bool {
2120 self.path_suffixes == other.path_suffixes
2121 && self.first_line_pattern.as_ref().map(Regex::as_str)
2122 == other.first_line_pattern.as_ref().map(Regex::as_str)
2123 }
2124}
2125
2126#[cfg(any(test, feature = "test-support"))]
2127impl Default for FakeLspAdapter {
2128 fn default() -> Self {
2129 Self {
2130 name: "the-fake-language-server",
2131 capabilities: lsp::LanguageServer::full_capabilities(),
2132 initializer: None,
2133 disk_based_diagnostics_progress_token: None,
2134 initialization_options: None,
2135 disk_based_diagnostics_sources: Vec::new(),
2136 prettier_plugins: Vec::new(),
2137 language_server_binary: LanguageServerBinary {
2138 path: "/the/fake/lsp/path".into(),
2139 arguments: vec![],
2140 env: Default::default(),
2141 },
2142 label_for_completion: None,
2143 }
2144 }
2145}
2146
2147#[cfg(any(test, feature = "test-support"))]
2148#[async_trait(?Send)]
2149impl LspAdapter for FakeLspAdapter {
2150 fn name(&self) -> LanguageServerName {
2151 LanguageServerName(self.name.into())
2152 }
2153
2154 async fn check_if_user_installed(
2155 &self,
2156 _: &dyn LspAdapterDelegate,
2157 _: Arc<dyn LanguageToolchainStore>,
2158 _: &AsyncApp,
2159 ) -> Option<LanguageServerBinary> {
2160 Some(self.language_server_binary.clone())
2161 }
2162
2163 fn get_language_server_command<'a>(
2164 self: Arc<Self>,
2165 _: Arc<dyn LspAdapterDelegate>,
2166 _: Arc<dyn LanguageToolchainStore>,
2167 _: LanguageServerBinaryOptions,
2168 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2169 _: &'a mut AsyncApp,
2170 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2171 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2172 }
2173
2174 async fn fetch_latest_server_version(
2175 &self,
2176 _: &dyn LspAdapterDelegate,
2177 ) -> Result<Box<dyn 'static + Send + Any>> {
2178 unreachable!();
2179 }
2180
2181 async fn fetch_server_binary(
2182 &self,
2183 _: Box<dyn 'static + Send + Any>,
2184 _: PathBuf,
2185 _: &dyn LspAdapterDelegate,
2186 ) -> Result<LanguageServerBinary> {
2187 unreachable!();
2188 }
2189
2190 async fn cached_server_binary(
2191 &self,
2192 _: PathBuf,
2193 _: &dyn LspAdapterDelegate,
2194 ) -> Option<LanguageServerBinary> {
2195 unreachable!();
2196 }
2197
2198 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2199 self.disk_based_diagnostics_sources.clone()
2200 }
2201
2202 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2203 self.disk_based_diagnostics_progress_token.clone()
2204 }
2205
2206 async fn initialization_options(
2207 self: Arc<Self>,
2208 _: &dyn Fs,
2209 _: &Arc<dyn LspAdapterDelegate>,
2210 ) -> Result<Option<Value>> {
2211 Ok(self.initialization_options.clone())
2212 }
2213
2214 async fn label_for_completion(
2215 &self,
2216 item: &lsp::CompletionItem,
2217 language: &Arc<Language>,
2218 ) -> Option<CodeLabel> {
2219 let label_for_completion = self.label_for_completion.as_ref()?;
2220 label_for_completion(item, language)
2221 }
2222}
2223
2224fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2225 for (ix, name) in query.capture_names().iter().enumerate() {
2226 for (capture_name, index) in captures.iter_mut() {
2227 if capture_name == name {
2228 **index = Some(ix as u32);
2229 break;
2230 }
2231 }
2232 }
2233}
2234
2235pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2236 lsp::Position::new(point.row, point.column)
2237}
2238
2239pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2240 Unclipped(PointUtf16::new(point.line, point.character))
2241}
2242
2243pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2244 anyhow::ensure!(
2245 range.start <= range.end,
2246 "Inverted range provided to an LSP request: {:?}-{:?}",
2247 range.start,
2248 range.end
2249 );
2250 Ok(lsp::Range {
2251 start: point_to_lsp(range.start),
2252 end: point_to_lsp(range.end),
2253 })
2254}
2255
2256pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2257 let mut start = point_from_lsp(range.start);
2258 let mut end = point_from_lsp(range.end);
2259 if start > end {
2260 log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2261 mem::swap(&mut start, &mut end);
2262 }
2263 start..end
2264}
2265
2266#[cfg(test)]
2267mod tests {
2268 use super::*;
2269 use gpui::TestAppContext;
2270
2271 #[gpui::test(iterations = 10)]
2272 async fn test_language_loading(cx: &mut TestAppContext) {
2273 let languages = LanguageRegistry::test(cx.executor());
2274 let languages = Arc::new(languages);
2275 languages.register_native_grammars([
2276 ("json", tree_sitter_json::LANGUAGE),
2277 ("rust", tree_sitter_rust::LANGUAGE),
2278 ]);
2279 languages.register_test_language(LanguageConfig {
2280 name: "JSON".into(),
2281 grammar: Some("json".into()),
2282 matcher: LanguageMatcher {
2283 path_suffixes: vec!["json".into()],
2284 ..Default::default()
2285 },
2286 ..Default::default()
2287 });
2288 languages.register_test_language(LanguageConfig {
2289 name: "Rust".into(),
2290 grammar: Some("rust".into()),
2291 matcher: LanguageMatcher {
2292 path_suffixes: vec!["rs".into()],
2293 ..Default::default()
2294 },
2295 ..Default::default()
2296 });
2297 assert_eq!(
2298 languages.language_names(),
2299 &[
2300 "JSON".to_string(),
2301 "Plain Text".to_string(),
2302 "Rust".to_string(),
2303 ]
2304 );
2305
2306 let rust1 = languages.language_for_name("Rust");
2307 let rust2 = languages.language_for_name("Rust");
2308
2309 // Ensure language is still listed even if it's being loaded.
2310 assert_eq!(
2311 languages.language_names(),
2312 &[
2313 "JSON".to_string(),
2314 "Plain Text".to_string(),
2315 "Rust".to_string(),
2316 ]
2317 );
2318
2319 let (rust1, rust2) = futures::join!(rust1, rust2);
2320 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2321
2322 // Ensure language is still listed even after loading it.
2323 assert_eq!(
2324 languages.language_names(),
2325 &[
2326 "JSON".to_string(),
2327 "Plain Text".to_string(),
2328 "Rust".to_string(),
2329 ]
2330 );
2331
2332 // Loading an unknown language returns an error.
2333 assert!(languages.language_for_name("Unknown").await.is_err());
2334 }
2335
2336 #[gpui::test]
2337 async fn test_completion_label_omits_duplicate_data() {
2338 let regular_completion_item_1 = lsp::CompletionItem {
2339 label: "regular1".to_string(),
2340 detail: Some("detail1".to_string()),
2341 label_details: Some(lsp::CompletionItemLabelDetails {
2342 detail: None,
2343 description: Some("description 1".to_string()),
2344 }),
2345 ..lsp::CompletionItem::default()
2346 };
2347
2348 let regular_completion_item_2 = lsp::CompletionItem {
2349 label: "regular2".to_string(),
2350 label_details: Some(lsp::CompletionItemLabelDetails {
2351 detail: None,
2352 description: Some("description 2".to_string()),
2353 }),
2354 ..lsp::CompletionItem::default()
2355 };
2356
2357 let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2358 detail: Some(regular_completion_item_1.label.clone()),
2359 ..regular_completion_item_1.clone()
2360 };
2361
2362 let completion_item_with_duplicate_detail = lsp::CompletionItem {
2363 detail: Some(regular_completion_item_1.label.clone()),
2364 label_details: None,
2365 ..regular_completion_item_1.clone()
2366 };
2367
2368 let completion_item_with_duplicate_description = lsp::CompletionItem {
2369 label_details: Some(lsp::CompletionItemLabelDetails {
2370 detail: None,
2371 description: Some(regular_completion_item_2.label.clone()),
2372 }),
2373 ..regular_completion_item_2.clone()
2374 };
2375
2376 assert_eq!(
2377 CodeLabel::fallback_for_completion(®ular_completion_item_1, None).text,
2378 format!(
2379 "{} {}",
2380 regular_completion_item_1.label,
2381 regular_completion_item_1.detail.unwrap()
2382 ),
2383 "LSP completion items with both detail and label_details.description should prefer detail"
2384 );
2385 assert_eq!(
2386 CodeLabel::fallback_for_completion(®ular_completion_item_2, None).text,
2387 format!(
2388 "{} {}",
2389 regular_completion_item_2.label,
2390 regular_completion_item_2
2391 .label_details
2392 .as_ref()
2393 .unwrap()
2394 .description
2395 .as_ref()
2396 .unwrap()
2397 ),
2398 "LSP completion items without detail but with label_details.description should use that"
2399 );
2400 assert_eq!(
2401 CodeLabel::fallback_for_completion(
2402 &completion_item_with_duplicate_detail_and_proper_description,
2403 None
2404 )
2405 .text,
2406 format!(
2407 "{} {}",
2408 regular_completion_item_1.label,
2409 regular_completion_item_1
2410 .label_details
2411 .as_ref()
2412 .unwrap()
2413 .description
2414 .as_ref()
2415 .unwrap()
2416 ),
2417 "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2418 );
2419 assert_eq!(
2420 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2421 regular_completion_item_1.label,
2422 "LSP completion items with duplicate label and detail, should omit the detail"
2423 );
2424 assert_eq!(
2425 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2426 .text,
2427 regular_completion_item_2.label,
2428 "LSP completion items with duplicate label and detail, should omit the detail"
2429 );
2430 }
2431}