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