1//! Provides `language`-related settings.
2
3use crate::{File, Language, LanguageName, LanguageServerName};
4use anyhow::Result;
5use collections::{HashMap, HashSet};
6use core::slice;
7use ec4rs::{
8 Properties as EditorconfigProperties,
9 property::{FinalNewline, IndentSize, IndentStyle, TabWidth, TrimTrailingWs},
10};
11use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
12use gpui::{App, Modifiers};
13use itertools::{Either, Itertools};
14use schemars::{
15 JsonSchema,
16 schema::{InstanceType, ObjectValidation, Schema, SchemaObject, SingleOrVec},
17};
18use serde::{
19 Deserialize, Deserializer, Serialize,
20 de::{self, IntoDeserializer, MapAccess, SeqAccess, Visitor},
21};
22use serde_json::Value;
23use settings::{
24 Settings, SettingsLocation, SettingsSources, SettingsStore, add_references_to_properties,
25};
26use std::{borrow::Cow, num::NonZeroU32, path::Path, sync::Arc};
27use util::serde::default_true;
28
29/// Initializes the language settings.
30pub fn init(cx: &mut App) {
31 AllLanguageSettings::register(cx);
32}
33
34/// Returns the settings for the specified language from the provided file.
35pub fn language_settings<'a>(
36 language: Option<LanguageName>,
37 file: Option<&'a Arc<dyn File>>,
38 cx: &'a App,
39) -> Cow<'a, LanguageSettings> {
40 let location = file.map(|f| SettingsLocation {
41 worktree_id: f.worktree_id(cx),
42 path: f.path().as_ref(),
43 });
44 AllLanguageSettings::get(location, cx).language(location, language.as_ref(), cx)
45}
46
47/// Returns the settings for all languages from the provided file.
48pub fn all_language_settings<'a>(
49 file: Option<&'a Arc<dyn File>>,
50 cx: &'a App,
51) -> &'a AllLanguageSettings {
52 let location = file.map(|f| SettingsLocation {
53 worktree_id: f.worktree_id(cx),
54 path: f.path().as_ref(),
55 });
56 AllLanguageSettings::get(location, cx)
57}
58
59/// The settings for all languages.
60#[derive(Debug, Clone)]
61pub struct AllLanguageSettings {
62 /// The edit prediction settings.
63 pub edit_predictions: EditPredictionSettings,
64 pub defaults: LanguageSettings,
65 languages: HashMap<LanguageName, LanguageSettings>,
66 pub(crate) file_types: HashMap<Arc<str>, GlobSet>,
67}
68
69/// The settings for a particular language.
70#[derive(Debug, Clone, Deserialize)]
71pub struct LanguageSettings {
72 /// How many columns a tab should occupy.
73 pub tab_size: NonZeroU32,
74 /// Whether to indent lines using tab characters, as opposed to multiple
75 /// spaces.
76 pub hard_tabs: bool,
77 /// How to soft-wrap long lines of text.
78 pub soft_wrap: SoftWrap,
79 /// The column at which to soft-wrap lines, for buffers where soft-wrap
80 /// is enabled.
81 pub preferred_line_length: u32,
82 /// Whether to show wrap guides (vertical rulers) in the editor.
83 /// Setting this to true will show a guide at the 'preferred_line_length' value
84 /// if softwrap is set to 'preferred_line_length', and will show any
85 /// additional guides as specified by the 'wrap_guides' setting.
86 pub show_wrap_guides: bool,
87 /// Character counts at which to show wrap guides (vertical rulers) in the editor.
88 pub wrap_guides: Vec<usize>,
89 /// Indent guide related settings.
90 pub indent_guides: IndentGuideSettings,
91 /// Whether or not to perform a buffer format before saving.
92 pub format_on_save: FormatOnSave,
93 /// Whether or not to remove any trailing whitespace from lines of a buffer
94 /// before saving it.
95 pub remove_trailing_whitespace_on_save: bool,
96 /// Whether or not to ensure there's a single newline at the end of a buffer
97 /// when saving it.
98 pub ensure_final_newline_on_save: bool,
99 /// How to perform a buffer format.
100 pub formatter: SelectedFormatter,
101 /// Zed's Prettier integration settings.
102 pub prettier: PrettierSettings,
103 /// Whether to automatically close JSX tags.
104 pub jsx_tag_auto_close: JsxTagAutoCloseSettings,
105 /// Whether to use language servers to provide code intelligence.
106 pub enable_language_server: bool,
107 /// The list of language servers to use (or disable) for this language.
108 ///
109 /// This array should consist of language server IDs, as well as the following
110 /// special tokens:
111 /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
112 /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
113 pub language_servers: Vec<String>,
114 /// Controls where the `editor::Rewrap` action is allowed for this language.
115 ///
116 /// Note: This setting has no effect in Vim mode, as rewrap is already
117 /// allowed everywhere.
118 pub allow_rewrap: RewrapBehavior,
119 /// Controls whether edit predictions are shown immediately (true)
120 /// or manually by triggering `editor::ShowEditPrediction` (false).
121 pub show_edit_predictions: bool,
122 /// Controls whether edit predictions are shown in the given language
123 /// scopes.
124 pub edit_predictions_disabled_in: Vec<String>,
125 /// Whether to show tabs and spaces in the editor.
126 pub show_whitespaces: ShowWhitespaceSetting,
127 /// Whether to start a new line with a comment when a previous line is a comment as well.
128 pub extend_comment_on_newline: bool,
129 /// Inlay hint related settings.
130 pub inlay_hints: InlayHintSettings,
131 /// Whether to automatically close brackets.
132 pub use_autoclose: bool,
133 /// Whether to automatically surround text with brackets.
134 pub use_auto_surround: bool,
135 /// Whether to use additional LSP queries to format (and amend) the code after
136 /// every "trigger" symbol input, defined by LSP server capabilities.
137 pub use_on_type_format: bool,
138 /// Whether indentation of pasted content should be adjusted based on the context.
139 pub auto_indent_on_paste: bool,
140 /// Controls how the editor handles the autoclosed characters.
141 pub always_treat_brackets_as_autoclosed: bool,
142 /// Which code actions to run on save
143 pub code_actions_on_format: HashMap<String, bool>,
144 /// Whether to perform linked edits
145 pub linked_edits: bool,
146 /// Task configuration for this language.
147 pub tasks: LanguageTaskConfig,
148 /// Whether to pop the completions menu while typing in an editor without
149 /// explicitly requesting it.
150 pub show_completions_on_input: bool,
151 /// Whether to display inline and alongside documentation for items in the
152 /// completions menu.
153 pub show_completion_documentation: bool,
154 /// Completion settings for this language.
155 pub completions: CompletionSettings,
156}
157
158impl LanguageSettings {
159 /// A token representing the rest of the available language servers.
160 const REST_OF_LANGUAGE_SERVERS: &'static str = "...";
161
162 /// Returns the customized list of language servers from the list of
163 /// available language servers.
164 pub fn customized_language_servers(
165 &self,
166 available_language_servers: &[LanguageServerName],
167 ) -> Vec<LanguageServerName> {
168 Self::resolve_language_servers(&self.language_servers, available_language_servers)
169 }
170
171 pub(crate) fn resolve_language_servers(
172 configured_language_servers: &[String],
173 available_language_servers: &[LanguageServerName],
174 ) -> Vec<LanguageServerName> {
175 let (disabled_language_servers, enabled_language_servers): (
176 Vec<LanguageServerName>,
177 Vec<LanguageServerName>,
178 ) = configured_language_servers.iter().partition_map(
179 |language_server| match language_server.strip_prefix('!') {
180 Some(disabled) => Either::Left(LanguageServerName(disabled.to_string().into())),
181 None => Either::Right(LanguageServerName(language_server.clone().into())),
182 },
183 );
184
185 let rest = available_language_servers
186 .iter()
187 .filter(|&available_language_server| {
188 !disabled_language_servers.contains(&available_language_server)
189 && !enabled_language_servers.contains(&available_language_server)
190 })
191 .cloned()
192 .collect::<Vec<_>>();
193
194 enabled_language_servers
195 .into_iter()
196 .flat_map(|language_server| {
197 if language_server.0.as_ref() == Self::REST_OF_LANGUAGE_SERVERS {
198 rest.clone()
199 } else {
200 vec![language_server.clone()]
201 }
202 })
203 .collect::<Vec<_>>()
204 }
205}
206
207/// The provider that supplies edit predictions.
208#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
209#[serde(rename_all = "snake_case")]
210pub enum EditPredictionProvider {
211 None,
212 #[default]
213 Copilot,
214 Supermaven,
215 Zed,
216}
217
218impl EditPredictionProvider {
219 pub fn is_zed(&self) -> bool {
220 match self {
221 EditPredictionProvider::Zed => true,
222 EditPredictionProvider::None
223 | EditPredictionProvider::Copilot
224 | EditPredictionProvider::Supermaven => false,
225 }
226 }
227}
228
229/// The settings for edit predictions, such as [GitHub Copilot](https://github.com/features/copilot)
230/// or [Supermaven](https://supermaven.com).
231#[derive(Clone, Debug, Default)]
232pub struct EditPredictionSettings {
233 /// The provider that supplies edit predictions.
234 pub provider: EditPredictionProvider,
235 /// A list of globs representing files that edit predictions should be disabled for.
236 /// This list adds to a pre-existing, sensible default set of globs.
237 /// Any additional ones you add are combined with them.
238 pub disabled_globs: Vec<DisabledGlob>,
239 /// Configures how edit predictions are displayed in the buffer.
240 pub mode: EditPredictionsMode,
241 /// Settings specific to GitHub Copilot.
242 pub copilot: CopilotSettings,
243 /// Whether edit predictions are enabled in the assistant panel.
244 /// This setting has no effect if globally disabled.
245 pub enabled_in_assistant: bool,
246}
247
248impl EditPredictionSettings {
249 /// Returns whether edit predictions are enabled for the given path.
250 pub fn enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
251 !self.disabled_globs.iter().any(|glob| {
252 if glob.is_absolute {
253 file.as_local()
254 .map_or(false, |local| glob.matcher.is_match(local.abs_path(cx)))
255 } else {
256 glob.matcher.is_match(file.path())
257 }
258 })
259 }
260}
261
262#[derive(Clone, Debug)]
263pub struct DisabledGlob {
264 matcher: GlobMatcher,
265 is_absolute: bool,
266}
267
268/// The mode in which edit predictions should be displayed.
269#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
270#[serde(rename_all = "snake_case")]
271pub enum EditPredictionsMode {
272 /// If provider supports it, display inline when holding modifier key (e.g., alt).
273 /// Otherwise, eager preview is used.
274 #[serde(alias = "auto")]
275 Subtle,
276 /// Display inline when there are no language server completions available.
277 #[default]
278 #[serde(alias = "eager_preview")]
279 Eager,
280}
281
282#[derive(Clone, Debug, Default)]
283pub struct CopilotSettings {
284 /// HTTP/HTTPS proxy to use for Copilot.
285 pub proxy: Option<String>,
286 /// Disable certificate verification for proxy (not recommended).
287 pub proxy_no_verify: Option<bool>,
288}
289
290/// The settings for all languages.
291#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
292pub struct AllLanguageSettingsContent {
293 /// The settings for enabling/disabling features.
294 #[serde(default)]
295 pub features: Option<FeaturesContent>,
296 /// The edit prediction settings.
297 #[serde(default)]
298 pub edit_predictions: Option<EditPredictionSettingsContent>,
299 /// The default language settings.
300 #[serde(flatten)]
301 pub defaults: LanguageSettingsContent,
302 /// The settings for individual languages.
303 #[serde(default)]
304 pub languages: HashMap<LanguageName, LanguageSettingsContent>,
305 /// Settings for associating file extensions and filenames
306 /// with languages.
307 #[serde(default)]
308 pub file_types: HashMap<Arc<str>, Vec<String>>,
309}
310
311/// Controls how completions are processed for this language.
312#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
313#[serde(rename_all = "snake_case")]
314pub struct CompletionSettings {
315 /// Controls how words are completed.
316 /// For large documents, not all words may be fetched for completion.
317 ///
318 /// Default: `fallback`
319 #[serde(default = "default_words_completion_mode")]
320 pub words: WordsCompletionMode,
321 /// Whether to fetch LSP completions or not.
322 ///
323 /// Default: true
324 #[serde(default = "default_true")]
325 pub lsp: bool,
326 /// When fetching LSP completions, determines how long to wait for a response of a particular server.
327 /// When set to 0, waits indefinitely.
328 ///
329 /// Default: 0
330 #[serde(default = "default_lsp_fetch_timeout_ms")]
331 pub lsp_fetch_timeout_ms: u64,
332 /// Controls how LSP completions are inserted.
333 ///
334 /// Default: "replace_suffix"
335 #[serde(default = "default_lsp_insert_mode")]
336 pub lsp_insert_mode: LspInsertMode,
337}
338
339/// Controls how document's words are completed.
340#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
341#[serde(rename_all = "snake_case")]
342pub enum WordsCompletionMode {
343 /// Always fetch document's words for completions along with LSP completions.
344 Enabled,
345 /// Only if LSP response errors or times out,
346 /// use document's words to show completions.
347 Fallback,
348 /// Never fetch or complete document's words for completions.
349 /// (Word-based completions can still be queried via a separate action)
350 Disabled,
351}
352
353#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
354#[serde(rename_all = "snake_case")]
355pub enum LspInsertMode {
356 /// Replaces text before the cursor, using the `insert` range described in the LSP specification.
357 Insert,
358 /// Replaces text before and after the cursor, using the `replace` range described in the LSP specification.
359 Replace,
360 /// Behaves like `"replace"` if the text that would be replaced is a subsequence of the completion text,
361 /// and like `"insert"` otherwise.
362 ReplaceSubsequence,
363 /// Behaves like `"replace"` if the text after the cursor is a suffix of the completion, and like
364 /// `"insert"` otherwise.
365 ReplaceSuffix,
366}
367
368fn default_words_completion_mode() -> WordsCompletionMode {
369 WordsCompletionMode::Fallback
370}
371
372fn default_lsp_insert_mode() -> LspInsertMode {
373 LspInsertMode::Insert
374}
375
376fn default_lsp_fetch_timeout_ms() -> u64 {
377 0
378}
379
380/// The settings for a particular language.
381#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
382pub struct LanguageSettingsContent {
383 /// How many columns a tab should occupy.
384 ///
385 /// Default: 4
386 #[serde(default)]
387 pub tab_size: Option<NonZeroU32>,
388 /// Whether to indent lines using tab characters, as opposed to multiple
389 /// spaces.
390 ///
391 /// Default: false
392 #[serde(default)]
393 pub hard_tabs: Option<bool>,
394 /// How to soft-wrap long lines of text.
395 ///
396 /// Default: none
397 #[serde(default)]
398 pub soft_wrap: Option<SoftWrap>,
399 /// The column at which to soft-wrap lines, for buffers where soft-wrap
400 /// is enabled.
401 ///
402 /// Default: 80
403 #[serde(default)]
404 pub preferred_line_length: Option<u32>,
405 /// Whether to show wrap guides in the editor. Setting this to true will
406 /// show a guide at the 'preferred_line_length' value if softwrap is set to
407 /// 'preferred_line_length', and will show any additional guides as specified
408 /// by the 'wrap_guides' setting.
409 ///
410 /// Default: true
411 #[serde(default)]
412 pub show_wrap_guides: Option<bool>,
413 /// Character counts at which to show wrap guides in the editor.
414 ///
415 /// Default: []
416 #[serde(default)]
417 pub wrap_guides: Option<Vec<usize>>,
418 /// Indent guide related settings.
419 #[serde(default)]
420 pub indent_guides: Option<IndentGuideSettings>,
421 /// Whether or not to perform a buffer format before saving.
422 ///
423 /// Default: on
424 #[serde(default)]
425 pub format_on_save: Option<FormatOnSave>,
426 /// Whether or not to remove any trailing whitespace from lines of a buffer
427 /// before saving it.
428 ///
429 /// Default: true
430 #[serde(default)]
431 pub remove_trailing_whitespace_on_save: Option<bool>,
432 /// Whether or not to ensure there's a single newline at the end of a buffer
433 /// when saving it.
434 ///
435 /// Default: true
436 #[serde(default)]
437 pub ensure_final_newline_on_save: Option<bool>,
438 /// How to perform a buffer format.
439 ///
440 /// Default: auto
441 #[serde(default)]
442 pub formatter: Option<SelectedFormatter>,
443 /// Zed's Prettier integration settings.
444 /// Allows to enable/disable formatting with Prettier
445 /// and configure default Prettier, used when no project-level Prettier installation is found.
446 ///
447 /// Default: off
448 #[serde(default)]
449 pub prettier: Option<PrettierSettings>,
450 /// Whether to automatically close JSX tags.
451 #[serde(default)]
452 pub jsx_tag_auto_close: Option<JsxTagAutoCloseSettings>,
453 /// Whether to use language servers to provide code intelligence.
454 ///
455 /// Default: true
456 #[serde(default)]
457 pub enable_language_server: Option<bool>,
458 /// The list of language servers to use (or disable) for this language.
459 ///
460 /// This array should consist of language server IDs, as well as the following
461 /// special tokens:
462 /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
463 /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
464 ///
465 /// Default: ["..."]
466 #[serde(default)]
467 pub language_servers: Option<Vec<String>>,
468 /// Controls where the `editor::Rewrap` action is allowed for this language.
469 ///
470 /// Note: This setting has no effect in Vim mode, as rewrap is already
471 /// allowed everywhere.
472 ///
473 /// Default: "in_comments"
474 #[serde(default)]
475 pub allow_rewrap: Option<RewrapBehavior>,
476 /// Controls whether edit predictions are shown immediately (true)
477 /// or manually by triggering `editor::ShowEditPrediction` (false).
478 ///
479 /// Default: true
480 #[serde(default)]
481 pub show_edit_predictions: Option<bool>,
482 /// Controls whether edit predictions are shown in the given language
483 /// scopes.
484 ///
485 /// Example: ["string", "comment"]
486 ///
487 /// Default: []
488 #[serde(default)]
489 pub edit_predictions_disabled_in: Option<Vec<String>>,
490 /// Whether to show tabs and spaces in the editor.
491 #[serde(default)]
492 pub show_whitespaces: Option<ShowWhitespaceSetting>,
493 /// Whether to start a new line with a comment when a previous line is a comment as well.
494 ///
495 /// Default: true
496 #[serde(default)]
497 pub extend_comment_on_newline: Option<bool>,
498 /// Inlay hint related settings.
499 #[serde(default)]
500 pub inlay_hints: Option<InlayHintSettings>,
501 /// Whether to automatically type closing characters for you. For example,
502 /// when you type (, Zed will automatically add a closing ) at the correct position.
503 ///
504 /// Default: true
505 pub use_autoclose: Option<bool>,
506 /// Whether to automatically surround text with characters for you. For example,
507 /// when you select text and type (, Zed will automatically surround text with ().
508 ///
509 /// Default: true
510 pub use_auto_surround: Option<bool>,
511 /// Controls how the editor handles the autoclosed characters.
512 /// When set to `false`(default), skipping over and auto-removing of the closing characters
513 /// happen only for auto-inserted characters.
514 /// Otherwise(when `true`), the closing characters are always skipped over and auto-removed
515 /// no matter how they were inserted.
516 ///
517 /// Default: false
518 pub always_treat_brackets_as_autoclosed: Option<bool>,
519 /// Whether to use additional LSP queries to format (and amend) the code after
520 /// every "trigger" symbol input, defined by LSP server capabilities.
521 ///
522 /// Default: true
523 pub use_on_type_format: Option<bool>,
524 /// Which code actions to run on save after the formatter.
525 /// These are not run if formatting is off.
526 ///
527 /// Default: {} (or {"source.organizeImports": true} for Go).
528 pub code_actions_on_format: Option<HashMap<String, bool>>,
529 /// Whether to perform linked edits of associated ranges, if the language server supports it.
530 /// For example, when editing opening <html> tag, the contents of the closing </html> tag will be edited as well.
531 ///
532 /// Default: true
533 pub linked_edits: Option<bool>,
534 /// Whether indentation of pasted content should be adjusted based on the context.
535 ///
536 /// Default: true
537 pub auto_indent_on_paste: Option<bool>,
538 /// Task configuration for this language.
539 ///
540 /// Default: {}
541 pub tasks: Option<LanguageTaskConfig>,
542 /// Whether to pop the completions menu while typing in an editor without
543 /// explicitly requesting it.
544 ///
545 /// Default: true
546 pub show_completions_on_input: Option<bool>,
547 /// Whether to display inline and alongside documentation for items in the
548 /// completions menu.
549 ///
550 /// Default: true
551 pub show_completion_documentation: Option<bool>,
552 /// Controls how completions are processed for this language.
553 pub completions: Option<CompletionSettings>,
554}
555
556/// The behavior of `editor::Rewrap`.
557#[derive(Debug, PartialEq, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]
558#[serde(rename_all = "snake_case")]
559pub enum RewrapBehavior {
560 /// Only rewrap within comments.
561 #[default]
562 InComments,
563 /// Only rewrap within the current selection(s).
564 InSelections,
565 /// Allow rewrapping anywhere.
566 Anywhere,
567}
568
569/// The contents of the edit prediction settings.
570#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)]
571pub struct EditPredictionSettingsContent {
572 /// A list of globs representing files that edit predictions should be disabled for.
573 /// This list adds to a pre-existing, sensible default set of globs.
574 /// Any additional ones you add are combined with them.
575 #[serde(default)]
576 pub disabled_globs: Option<Vec<String>>,
577 /// The mode used to display edit predictions in the buffer.
578 /// Provider support required.
579 #[serde(default)]
580 pub mode: EditPredictionsMode,
581 /// Settings specific to GitHub Copilot.
582 #[serde(default)]
583 pub copilot: CopilotSettingsContent,
584 /// Whether edit predictions are enabled in the assistant prompt editor.
585 /// This has no effect if globally disabled.
586 #[serde(default = "default_true")]
587 pub enabled_in_assistant: bool,
588}
589
590#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)]
591pub struct CopilotSettingsContent {
592 /// HTTP/HTTPS proxy to use for Copilot.
593 ///
594 /// Default: none
595 #[serde(default)]
596 pub proxy: Option<String>,
597 /// Disable certificate verification for the proxy (not recommended).
598 ///
599 /// Default: false
600 #[serde(default)]
601 pub proxy_no_verify: Option<bool>,
602}
603
604/// The settings for enabling/disabling features.
605#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
606#[serde(rename_all = "snake_case")]
607pub struct FeaturesContent {
608 /// Determines which edit prediction provider to use.
609 pub edit_prediction_provider: Option<EditPredictionProvider>,
610}
611
612/// Controls the soft-wrapping behavior in the editor.
613#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
614#[serde(rename_all = "snake_case")]
615pub enum SoftWrap {
616 /// Prefer a single line generally, unless an overly long line is encountered.
617 None,
618 /// Deprecated: use None instead. Left to avoid breaking existing users' configs.
619 /// Prefer a single line generally, unless an overly long line is encountered.
620 PreferLine,
621 /// Soft wrap lines that exceed the editor width.
622 EditorWidth,
623 /// Soft wrap lines at the preferred line length.
624 PreferredLineLength,
625 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
626 Bounded,
627}
628
629/// Controls the behavior of formatting files when they are saved.
630#[derive(Debug, Clone, PartialEq, Eq)]
631pub enum FormatOnSave {
632 /// Files should be formatted on save.
633 On,
634 /// Files should not be formatted on save.
635 Off,
636 List(FormatterList),
637}
638
639impl JsonSchema for FormatOnSave {
640 fn schema_name() -> String {
641 "OnSaveFormatter".into()
642 }
643
644 fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> Schema {
645 let mut schema = SchemaObject::default();
646 let formatter_schema = Formatter::json_schema(generator);
647 schema.instance_type = Some(
648 vec![
649 InstanceType::Object,
650 InstanceType::String,
651 InstanceType::Array,
652 ]
653 .into(),
654 );
655
656 let valid_raw_values = SchemaObject {
657 enum_values: Some(vec![
658 Value::String("on".into()),
659 Value::String("off".into()),
660 Value::String("prettier".into()),
661 Value::String("language_server".into()),
662 ]),
663 ..Default::default()
664 };
665 let mut nested_values = SchemaObject::default();
666
667 nested_values.array().items = Some(formatter_schema.clone().into());
668
669 schema.subschemas().any_of = Some(vec![
670 nested_values.into(),
671 valid_raw_values.into(),
672 formatter_schema,
673 ]);
674 schema.into()
675 }
676}
677
678impl Serialize for FormatOnSave {
679 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
680 where
681 S: serde::Serializer,
682 {
683 match self {
684 Self::On => serializer.serialize_str("on"),
685 Self::Off => serializer.serialize_str("off"),
686 Self::List(list) => list.serialize(serializer),
687 }
688 }
689}
690
691impl<'de> Deserialize<'de> for FormatOnSave {
692 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
693 where
694 D: Deserializer<'de>,
695 {
696 struct FormatDeserializer;
697
698 impl<'d> Visitor<'d> for FormatDeserializer {
699 type Value = FormatOnSave;
700
701 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
702 formatter.write_str("a valid on-save formatter kind")
703 }
704 fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
705 where
706 E: serde::de::Error,
707 {
708 if v == "on" {
709 Ok(Self::Value::On)
710 } else if v == "off" {
711 Ok(Self::Value::Off)
712 } else if v == "language_server" {
713 Ok(Self::Value::List(FormatterList(
714 Formatter::LanguageServer { name: None }.into(),
715 )))
716 } else {
717 let ret: Result<FormatterList, _> =
718 Deserialize::deserialize(v.into_deserializer());
719 ret.map(Self::Value::List)
720 }
721 }
722 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
723 where
724 A: MapAccess<'d>,
725 {
726 let ret: Result<FormatterList, _> =
727 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
728 ret.map(Self::Value::List)
729 }
730 fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
731 where
732 A: SeqAccess<'d>,
733 {
734 let ret: Result<FormatterList, _> =
735 Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
736 ret.map(Self::Value::List)
737 }
738 }
739 deserializer.deserialize_any(FormatDeserializer)
740 }
741}
742
743/// Controls how whitespace should be displayedin the editor.
744#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
745#[serde(rename_all = "snake_case")]
746pub enum ShowWhitespaceSetting {
747 /// Draw whitespace only for the selected text.
748 Selection,
749 /// Do not draw any tabs or spaces.
750 None,
751 /// Draw all invisible symbols.
752 All,
753 /// Draw whitespaces at boundaries only.
754 ///
755 /// For a whitespace to be on a boundary, any of the following conditions need to be met:
756 /// - It is a tab
757 /// - It is adjacent to an edge (start or end)
758 /// - It is adjacent to a whitespace (left or right)
759 Boundary,
760}
761
762/// Controls which formatter should be used when formatting code.
763#[derive(Clone, Debug, Default, PartialEq, Eq)]
764pub enum SelectedFormatter {
765 /// Format files using Zed's Prettier integration (if applicable),
766 /// or falling back to formatting via language server.
767 #[default]
768 Auto,
769 List(FormatterList),
770}
771
772impl JsonSchema for SelectedFormatter {
773 fn schema_name() -> String {
774 "Formatter".into()
775 }
776
777 fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> Schema {
778 let mut schema = SchemaObject::default();
779 let formatter_schema = Formatter::json_schema(generator);
780 schema.instance_type = Some(
781 vec![
782 InstanceType::Object,
783 InstanceType::String,
784 InstanceType::Array,
785 ]
786 .into(),
787 );
788
789 let valid_raw_values = SchemaObject {
790 enum_values: Some(vec![
791 Value::String("auto".into()),
792 Value::String("prettier".into()),
793 Value::String("language_server".into()),
794 ]),
795 ..Default::default()
796 };
797
798 let mut nested_values = SchemaObject::default();
799
800 nested_values.array().items = Some(formatter_schema.clone().into());
801
802 schema.subschemas().any_of = Some(vec![
803 nested_values.into(),
804 valid_raw_values.into(),
805 formatter_schema,
806 ]);
807 schema.into()
808 }
809}
810
811impl Serialize for SelectedFormatter {
812 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
813 where
814 S: serde::Serializer,
815 {
816 match self {
817 SelectedFormatter::Auto => serializer.serialize_str("auto"),
818 SelectedFormatter::List(list) => list.serialize(serializer),
819 }
820 }
821}
822impl<'de> Deserialize<'de> for SelectedFormatter {
823 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
824 where
825 D: Deserializer<'de>,
826 {
827 struct FormatDeserializer;
828
829 impl<'d> Visitor<'d> for FormatDeserializer {
830 type Value = SelectedFormatter;
831
832 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
833 formatter.write_str("a valid formatter kind")
834 }
835 fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
836 where
837 E: serde::de::Error,
838 {
839 if v == "auto" {
840 Ok(Self::Value::Auto)
841 } else if v == "language_server" {
842 Ok(Self::Value::List(FormatterList(
843 Formatter::LanguageServer { name: None }.into(),
844 )))
845 } else {
846 let ret: Result<FormatterList, _> =
847 Deserialize::deserialize(v.into_deserializer());
848 ret.map(SelectedFormatter::List)
849 }
850 }
851 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
852 where
853 A: MapAccess<'d>,
854 {
855 let ret: Result<FormatterList, _> =
856 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
857 ret.map(SelectedFormatter::List)
858 }
859 fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
860 where
861 A: SeqAccess<'d>,
862 {
863 let ret: Result<FormatterList, _> =
864 Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
865 ret.map(SelectedFormatter::List)
866 }
867 }
868 deserializer.deserialize_any(FormatDeserializer)
869 }
870}
871/// Controls which formatter should be used when formatting code.
872#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
873#[serde(rename_all = "snake_case", transparent)]
874pub struct FormatterList(pub SingleOrVec<Formatter>);
875
876impl AsRef<[Formatter]> for FormatterList {
877 fn as_ref(&self) -> &[Formatter] {
878 match &self.0 {
879 SingleOrVec::Single(single) => slice::from_ref(single),
880 SingleOrVec::Vec(v) => v,
881 }
882 }
883}
884
885/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
886#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
887#[serde(rename_all = "snake_case")]
888pub enum Formatter {
889 /// Format code using the current language server.
890 LanguageServer { name: Option<String> },
891 /// Format code using Zed's Prettier integration.
892 Prettier,
893 /// Format code using an external command.
894 External {
895 /// The external program to run.
896 command: Arc<str>,
897 /// The arguments to pass to the program.
898 arguments: Option<Arc<[String]>>,
899 },
900 /// Files should be formatted using code actions executed by language servers.
901 CodeActions(HashMap<String, bool>),
902}
903
904/// The settings for indent guides.
905#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
906pub struct IndentGuideSettings {
907 /// Whether to display indent guides in the editor.
908 ///
909 /// Default: true
910 #[serde(default = "default_true")]
911 pub enabled: bool,
912 /// The width of the indent guides in pixels, between 1 and 10.
913 ///
914 /// Default: 1
915 #[serde(default = "line_width")]
916 pub line_width: u32,
917 /// The width of the active indent guide in pixels, between 1 and 10.
918 ///
919 /// Default: 1
920 #[serde(default = "active_line_width")]
921 pub active_line_width: u32,
922 /// Determines how indent guides are colored.
923 ///
924 /// Default: Fixed
925 #[serde(default)]
926 pub coloring: IndentGuideColoring,
927 /// Determines how indent guide backgrounds are colored.
928 ///
929 /// Default: Disabled
930 #[serde(default)]
931 pub background_coloring: IndentGuideBackgroundColoring,
932}
933
934fn line_width() -> u32 {
935 1
936}
937
938fn active_line_width() -> u32 {
939 line_width()
940}
941
942/// Determines how indent guides are colored.
943#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
944#[serde(rename_all = "snake_case")]
945pub enum IndentGuideColoring {
946 /// Do not render any lines for indent guides.
947 Disabled,
948 /// Use the same color for all indentation levels.
949 #[default]
950 Fixed,
951 /// Use a different color for each indentation level.
952 IndentAware,
953}
954
955/// Determines how indent guide backgrounds are colored.
956#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
957#[serde(rename_all = "snake_case")]
958pub enum IndentGuideBackgroundColoring {
959 /// Do not render any background for indent guides.
960 #[default]
961 Disabled,
962 /// Use a different color for each indentation level.
963 IndentAware,
964}
965
966/// The settings for inlay hints.
967#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
968pub struct InlayHintSettings {
969 /// Global switch to toggle hints on and off.
970 ///
971 /// Default: false
972 #[serde(default)]
973 pub enabled: bool,
974 /// Whether type hints should be shown.
975 ///
976 /// Default: true
977 #[serde(default = "default_true")]
978 pub show_type_hints: bool,
979 /// Whether parameter hints should be shown.
980 ///
981 /// Default: true
982 #[serde(default = "default_true")]
983 pub show_parameter_hints: bool,
984 /// Whether other hints should be shown.
985 ///
986 /// Default: true
987 #[serde(default = "default_true")]
988 pub show_other_hints: bool,
989 /// Whether to show a background for inlay hints.
990 ///
991 /// If set to `true`, the background will use the `hint.background` color
992 /// from the current theme.
993 ///
994 /// Default: false
995 #[serde(default)]
996 pub show_background: bool,
997 /// Whether or not to debounce inlay hints updates after buffer edits.
998 ///
999 /// Set to 0 to disable debouncing.
1000 ///
1001 /// Default: 700
1002 #[serde(default = "edit_debounce_ms")]
1003 pub edit_debounce_ms: u64,
1004 /// Whether or not to debounce inlay hints updates after buffer scrolls.
1005 ///
1006 /// Set to 0 to disable debouncing.
1007 ///
1008 /// Default: 50
1009 #[serde(default = "scroll_debounce_ms")]
1010 pub scroll_debounce_ms: u64,
1011 /// Toggles inlay hints (hides or shows) when the user presses the modifiers specified.
1012 /// If only a subset of the modifiers specified is pressed, hints are not toggled.
1013 /// If no modifiers are specified, this is equivalent to `None`.
1014 ///
1015 /// Default: None
1016 #[serde(default)]
1017 pub toggle_on_modifiers_press: Option<Modifiers>,
1018}
1019
1020fn edit_debounce_ms() -> u64 {
1021 700
1022}
1023
1024fn scroll_debounce_ms() -> u64 {
1025 50
1026}
1027
1028/// The task settings for a particular language.
1029#[derive(Debug, Clone, Deserialize, PartialEq, Serialize, JsonSchema)]
1030pub struct LanguageTaskConfig {
1031 /// Extra task variables to set for a particular language.
1032 pub variables: HashMap<String, String>,
1033}
1034
1035impl InlayHintSettings {
1036 /// Returns the kinds of inlay hints that are enabled based on the settings.
1037 pub fn enabled_inlay_hint_kinds(&self) -> HashSet<Option<InlayHintKind>> {
1038 let mut kinds = HashSet::default();
1039 if self.show_type_hints {
1040 kinds.insert(Some(InlayHintKind::Type));
1041 }
1042 if self.show_parameter_hints {
1043 kinds.insert(Some(InlayHintKind::Parameter));
1044 }
1045 if self.show_other_hints {
1046 kinds.insert(None);
1047 }
1048 kinds
1049 }
1050}
1051
1052impl AllLanguageSettings {
1053 /// Returns the [`LanguageSettings`] for the language with the specified name.
1054 pub fn language<'a>(
1055 &'a self,
1056 location: Option<SettingsLocation<'a>>,
1057 language_name: Option<&LanguageName>,
1058 cx: &'a App,
1059 ) -> Cow<'a, LanguageSettings> {
1060 let settings = language_name
1061 .and_then(|name| self.languages.get(name))
1062 .unwrap_or(&self.defaults);
1063
1064 let editorconfig_properties = location.and_then(|location| {
1065 cx.global::<SettingsStore>()
1066 .editorconfig_properties(location.worktree_id, location.path)
1067 });
1068 if let Some(editorconfig_properties) = editorconfig_properties {
1069 let mut settings = settings.clone();
1070 merge_with_editorconfig(&mut settings, &editorconfig_properties);
1071 Cow::Owned(settings)
1072 } else {
1073 Cow::Borrowed(settings)
1074 }
1075 }
1076
1077 /// Returns whether edit predictions are enabled for the given path.
1078 pub fn edit_predictions_enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
1079 self.edit_predictions.enabled_for_file(file, cx)
1080 }
1081
1082 /// Returns whether edit predictions are enabled for the given language and path.
1083 pub fn show_edit_predictions(&self, language: Option<&Arc<Language>>, cx: &App) -> bool {
1084 self.language(None, language.map(|l| l.name()).as_ref(), cx)
1085 .show_edit_predictions
1086 }
1087
1088 /// Returns the edit predictions preview mode for the given language and path.
1089 pub fn edit_predictions_mode(&self) -> EditPredictionsMode {
1090 self.edit_predictions.mode
1091 }
1092}
1093
1094fn merge_with_editorconfig(settings: &mut LanguageSettings, cfg: &EditorconfigProperties) {
1095 let tab_size = cfg.get::<IndentSize>().ok().and_then(|v| match v {
1096 IndentSize::Value(u) => NonZeroU32::new(u as u32),
1097 IndentSize::UseTabWidth => cfg.get::<TabWidth>().ok().and_then(|w| match w {
1098 TabWidth::Value(u) => NonZeroU32::new(u as u32),
1099 }),
1100 });
1101 let hard_tabs = cfg
1102 .get::<IndentStyle>()
1103 .map(|v| v.eq(&IndentStyle::Tabs))
1104 .ok();
1105 let ensure_final_newline_on_save = cfg
1106 .get::<FinalNewline>()
1107 .map(|v| match v {
1108 FinalNewline::Value(b) => b,
1109 })
1110 .ok();
1111 let remove_trailing_whitespace_on_save = cfg
1112 .get::<TrimTrailingWs>()
1113 .map(|v| match v {
1114 TrimTrailingWs::Value(b) => b,
1115 })
1116 .ok();
1117 fn merge<T>(target: &mut T, value: Option<T>) {
1118 if let Some(value) = value {
1119 *target = value;
1120 }
1121 }
1122 merge(&mut settings.tab_size, tab_size);
1123 merge(&mut settings.hard_tabs, hard_tabs);
1124 merge(
1125 &mut settings.remove_trailing_whitespace_on_save,
1126 remove_trailing_whitespace_on_save,
1127 );
1128 merge(
1129 &mut settings.ensure_final_newline_on_save,
1130 ensure_final_newline_on_save,
1131 );
1132}
1133
1134/// The kind of an inlay hint.
1135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1136pub enum InlayHintKind {
1137 /// An inlay hint for a type.
1138 Type,
1139 /// An inlay hint for a parameter.
1140 Parameter,
1141}
1142
1143impl InlayHintKind {
1144 /// Returns the [`InlayHintKind`] from the given name.
1145 ///
1146 /// Returns `None` if `name` does not match any of the expected
1147 /// string representations.
1148 pub fn from_name(name: &str) -> Option<Self> {
1149 match name {
1150 "type" => Some(InlayHintKind::Type),
1151 "parameter" => Some(InlayHintKind::Parameter),
1152 _ => None,
1153 }
1154 }
1155
1156 /// Returns the name of this [`InlayHintKind`].
1157 pub fn name(&self) -> &'static str {
1158 match self {
1159 InlayHintKind::Type => "type",
1160 InlayHintKind::Parameter => "parameter",
1161 }
1162 }
1163}
1164
1165impl settings::Settings for AllLanguageSettings {
1166 const KEY: Option<&'static str> = None;
1167
1168 type FileContent = AllLanguageSettingsContent;
1169
1170 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1171 let default_value = sources.default;
1172
1173 // A default is provided for all settings.
1174 let mut defaults: LanguageSettings =
1175 serde_json::from_value(serde_json::to_value(&default_value.defaults)?)?;
1176
1177 let mut languages = HashMap::default();
1178 for (language_name, settings) in &default_value.languages {
1179 let mut language_settings = defaults.clone();
1180 merge_settings(&mut language_settings, settings);
1181 languages.insert(language_name.clone(), language_settings);
1182 }
1183
1184 let mut edit_prediction_provider = default_value
1185 .features
1186 .as_ref()
1187 .and_then(|f| f.edit_prediction_provider);
1188 let mut edit_predictions_mode = default_value
1189 .edit_predictions
1190 .as_ref()
1191 .map(|edit_predictions| edit_predictions.mode)
1192 .ok_or_else(Self::missing_default)?;
1193
1194 let mut completion_globs: HashSet<&String> = default_value
1195 .edit_predictions
1196 .as_ref()
1197 .and_then(|c| c.disabled_globs.as_ref())
1198 .map(|globs| globs.iter().collect())
1199 .ok_or_else(Self::missing_default)?;
1200
1201 let mut copilot_settings = default_value
1202 .edit_predictions
1203 .as_ref()
1204 .map(|settings| settings.copilot.clone())
1205 .map(|copilot| CopilotSettings {
1206 proxy: copilot.proxy,
1207 proxy_no_verify: copilot.proxy_no_verify,
1208 })
1209 .unwrap_or_default();
1210
1211 let mut edit_predictions_enabled_in_assistant = default_value
1212 .edit_predictions
1213 .as_ref()
1214 .map(|settings| settings.enabled_in_assistant)
1215 .unwrap_or(true);
1216
1217 let mut file_types: HashMap<Arc<str>, GlobSet> = HashMap::default();
1218
1219 for (language, suffixes) in &default_value.file_types {
1220 let mut builder = GlobSetBuilder::new();
1221
1222 for suffix in suffixes {
1223 builder.add(Glob::new(suffix)?);
1224 }
1225
1226 file_types.insert(language.clone(), builder.build()?);
1227 }
1228
1229 for user_settings in sources.customizations() {
1230 if let Some(provider) = user_settings
1231 .features
1232 .as_ref()
1233 .and_then(|f| f.edit_prediction_provider)
1234 {
1235 edit_prediction_provider = Some(provider);
1236 }
1237
1238 if let Some(edit_predictions) = user_settings.edit_predictions.as_ref() {
1239 edit_predictions_mode = edit_predictions.mode;
1240 edit_predictions_enabled_in_assistant = edit_predictions.enabled_in_assistant;
1241
1242 if let Some(disabled_globs) = edit_predictions.disabled_globs.as_ref() {
1243 completion_globs.extend(disabled_globs.iter());
1244 }
1245 }
1246
1247 if let Some(proxy) = user_settings
1248 .edit_predictions
1249 .as_ref()
1250 .and_then(|settings| settings.copilot.proxy.clone())
1251 {
1252 copilot_settings.proxy = Some(proxy);
1253 }
1254
1255 if let Some(proxy_no_verify) = user_settings
1256 .edit_predictions
1257 .as_ref()
1258 .and_then(|settings| settings.copilot.proxy_no_verify)
1259 {
1260 copilot_settings.proxy_no_verify = Some(proxy_no_verify);
1261 }
1262
1263 // A user's global settings override the default global settings and
1264 // all default language-specific settings.
1265 merge_settings(&mut defaults, &user_settings.defaults);
1266 for language_settings in languages.values_mut() {
1267 merge_settings(language_settings, &user_settings.defaults);
1268 }
1269
1270 // A user's language-specific settings override default language-specific settings.
1271 for (language_name, user_language_settings) in &user_settings.languages {
1272 merge_settings(
1273 languages
1274 .entry(language_name.clone())
1275 .or_insert_with(|| defaults.clone()),
1276 user_language_settings,
1277 );
1278 }
1279
1280 for (language, suffixes) in &user_settings.file_types {
1281 let mut builder = GlobSetBuilder::new();
1282
1283 let default_value = default_value.file_types.get(&language.clone());
1284
1285 // Merge the default value with the user's value.
1286 if let Some(suffixes) = default_value {
1287 for suffix in suffixes {
1288 builder.add(Glob::new(suffix)?);
1289 }
1290 }
1291
1292 for suffix in suffixes {
1293 builder.add(Glob::new(suffix)?);
1294 }
1295
1296 file_types.insert(language.clone(), builder.build()?);
1297 }
1298 }
1299
1300 Ok(Self {
1301 edit_predictions: EditPredictionSettings {
1302 provider: if let Some(provider) = edit_prediction_provider {
1303 provider
1304 } else {
1305 EditPredictionProvider::None
1306 },
1307 disabled_globs: completion_globs
1308 .iter()
1309 .filter_map(|g| {
1310 Some(DisabledGlob {
1311 matcher: globset::Glob::new(g).ok()?.compile_matcher(),
1312 is_absolute: Path::new(g).is_absolute(),
1313 })
1314 })
1315 .collect(),
1316 mode: edit_predictions_mode,
1317 copilot: copilot_settings,
1318 enabled_in_assistant: edit_predictions_enabled_in_assistant,
1319 },
1320 defaults,
1321 languages,
1322 file_types,
1323 })
1324 }
1325
1326 fn json_schema(
1327 generator: &mut schemars::r#gen::SchemaGenerator,
1328 params: &settings::SettingsJsonSchemaParams,
1329 _: &App,
1330 ) -> schemars::schema::RootSchema {
1331 let mut root_schema = generator.root_schema_for::<Self::FileContent>();
1332
1333 // Create a schema for a 'languages overrides' object, associating editor
1334 // settings with specific languages.
1335 assert!(
1336 root_schema
1337 .definitions
1338 .contains_key("LanguageSettingsContent")
1339 );
1340
1341 let languages_object_schema = SchemaObject {
1342 instance_type: Some(InstanceType::Object.into()),
1343 object: Some(Box::new(ObjectValidation {
1344 properties: params
1345 .language_names
1346 .iter()
1347 .map(|name| {
1348 (
1349 name.clone(),
1350 Schema::new_ref("#/definitions/LanguageSettingsContent".into()),
1351 )
1352 })
1353 .collect(),
1354 ..Default::default()
1355 })),
1356 ..Default::default()
1357 };
1358
1359 root_schema
1360 .definitions
1361 .extend([("Languages".into(), languages_object_schema.into())]);
1362
1363 add_references_to_properties(
1364 &mut root_schema,
1365 &[("languages", "#/definitions/Languages")],
1366 );
1367
1368 root_schema
1369 }
1370}
1371
1372fn merge_settings(settings: &mut LanguageSettings, src: &LanguageSettingsContent) {
1373 fn merge<T>(target: &mut T, value: Option<T>) {
1374 if let Some(value) = value {
1375 *target = value;
1376 }
1377 }
1378
1379 merge(&mut settings.tab_size, src.tab_size);
1380 settings.tab_size = settings
1381 .tab_size
1382 .clamp(NonZeroU32::new(1).unwrap(), NonZeroU32::new(16).unwrap());
1383
1384 merge(&mut settings.hard_tabs, src.hard_tabs);
1385 merge(&mut settings.soft_wrap, src.soft_wrap);
1386 merge(&mut settings.use_autoclose, src.use_autoclose);
1387 merge(&mut settings.use_auto_surround, src.use_auto_surround);
1388 merge(&mut settings.use_on_type_format, src.use_on_type_format);
1389 merge(&mut settings.auto_indent_on_paste, src.auto_indent_on_paste);
1390 merge(
1391 &mut settings.always_treat_brackets_as_autoclosed,
1392 src.always_treat_brackets_as_autoclosed,
1393 );
1394 merge(&mut settings.show_wrap_guides, src.show_wrap_guides);
1395 merge(&mut settings.wrap_guides, src.wrap_guides.clone());
1396 merge(&mut settings.indent_guides, src.indent_guides);
1397 merge(
1398 &mut settings.code_actions_on_format,
1399 src.code_actions_on_format.clone(),
1400 );
1401 merge(&mut settings.linked_edits, src.linked_edits);
1402 merge(&mut settings.tasks, src.tasks.clone());
1403
1404 merge(
1405 &mut settings.preferred_line_length,
1406 src.preferred_line_length,
1407 );
1408 merge(&mut settings.formatter, src.formatter.clone());
1409 merge(&mut settings.prettier, src.prettier.clone());
1410 merge(
1411 &mut settings.jsx_tag_auto_close,
1412 src.jsx_tag_auto_close.clone(),
1413 );
1414 merge(&mut settings.format_on_save, src.format_on_save.clone());
1415 merge(
1416 &mut settings.remove_trailing_whitespace_on_save,
1417 src.remove_trailing_whitespace_on_save,
1418 );
1419 merge(
1420 &mut settings.ensure_final_newline_on_save,
1421 src.ensure_final_newline_on_save,
1422 );
1423 merge(
1424 &mut settings.enable_language_server,
1425 src.enable_language_server,
1426 );
1427 merge(&mut settings.language_servers, src.language_servers.clone());
1428 merge(&mut settings.allow_rewrap, src.allow_rewrap);
1429 merge(
1430 &mut settings.show_edit_predictions,
1431 src.show_edit_predictions,
1432 );
1433 merge(
1434 &mut settings.edit_predictions_disabled_in,
1435 src.edit_predictions_disabled_in.clone(),
1436 );
1437 merge(&mut settings.show_whitespaces, src.show_whitespaces);
1438 merge(
1439 &mut settings.extend_comment_on_newline,
1440 src.extend_comment_on_newline,
1441 );
1442 merge(&mut settings.inlay_hints, src.inlay_hints);
1443 merge(
1444 &mut settings.show_completions_on_input,
1445 src.show_completions_on_input,
1446 );
1447 merge(
1448 &mut settings.show_completion_documentation,
1449 src.show_completion_documentation,
1450 );
1451 merge(&mut settings.completions, src.completions);
1452}
1453
1454/// Allows to enable/disable formatting with Prettier
1455/// and configure default Prettier, used when no project-level Prettier installation is found.
1456/// Prettier formatting is disabled by default.
1457#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1458pub struct PrettierSettings {
1459 /// Enables or disables formatting with Prettier for a given language.
1460 #[serde(default)]
1461 pub allowed: bool,
1462
1463 /// Forces Prettier integration to use a specific parser name when formatting files with the language.
1464 #[serde(default)]
1465 pub parser: Option<String>,
1466
1467 /// Forces Prettier integration to use specific plugins when formatting files with the language.
1468 /// The default Prettier will be installed with these plugins.
1469 #[serde(default)]
1470 pub plugins: HashSet<String>,
1471
1472 /// Default Prettier options, in the format as in package.json section for Prettier.
1473 /// If project installs Prettier via its package.json, these options will be ignored.
1474 #[serde(flatten)]
1475 pub options: HashMap<String, serde_json::Value>,
1476}
1477
1478#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1479pub struct JsxTagAutoCloseSettings {
1480 /// Enables or disables auto-closing of JSX tags.
1481 #[serde(default)]
1482 pub enabled: bool,
1483}
1484
1485#[cfg(test)]
1486mod tests {
1487 use gpui::TestAppContext;
1488
1489 use super::*;
1490
1491 #[test]
1492 fn test_formatter_deserialization() {
1493 let raw_auto = "{\"formatter\": \"auto\"}";
1494 let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
1495 assert_eq!(settings.formatter, Some(SelectedFormatter::Auto));
1496 let raw = "{\"formatter\": \"language_server\"}";
1497 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1498 assert_eq!(
1499 settings.formatter,
1500 Some(SelectedFormatter::List(FormatterList(
1501 Formatter::LanguageServer { name: None }.into()
1502 )))
1503 );
1504 let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
1505 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1506 assert_eq!(
1507 settings.formatter,
1508 Some(SelectedFormatter::List(FormatterList(
1509 vec![Formatter::LanguageServer { name: None }].into()
1510 )))
1511 );
1512 let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"prettier\"]}";
1513 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1514 assert_eq!(
1515 settings.formatter,
1516 Some(SelectedFormatter::List(FormatterList(
1517 vec![
1518 Formatter::LanguageServer { name: None },
1519 Formatter::Prettier
1520 ]
1521 .into()
1522 )))
1523 );
1524 }
1525
1526 #[test]
1527 fn test_formatter_deserialization_invalid() {
1528 let raw_auto = "{\"formatter\": {}}";
1529 let result: Result<LanguageSettingsContent, _> = serde_json::from_str(raw_auto);
1530 assert!(result.is_err());
1531 }
1532
1533 #[gpui::test]
1534 fn test_edit_predictions_enabled_for_file(cx: &mut TestAppContext) {
1535 use crate::TestFile;
1536 use std::path::PathBuf;
1537
1538 let cx = cx.app.borrow_mut();
1539
1540 let build_settings = |globs: &[&str]| -> EditPredictionSettings {
1541 EditPredictionSettings {
1542 disabled_globs: globs
1543 .iter()
1544 .map(|glob_str| {
1545 #[cfg(windows)]
1546 let glob_str = {
1547 let mut g = String::new();
1548
1549 if glob_str.starts_with('/') {
1550 g.push_str("C:");
1551 }
1552
1553 g.push_str(&glob_str.replace('/', "\\"));
1554 g
1555 };
1556 #[cfg(windows)]
1557 let glob_str = glob_str.as_str();
1558
1559 DisabledGlob {
1560 matcher: globset::Glob::new(glob_str).unwrap().compile_matcher(),
1561 is_absolute: Path::new(glob_str).is_absolute(),
1562 }
1563 })
1564 .collect(),
1565 ..Default::default()
1566 }
1567 };
1568
1569 const WORKTREE_NAME: &str = "project";
1570 let make_test_file = |segments: &[&str]| -> Arc<dyn File> {
1571 let mut path_buf = PathBuf::new();
1572 path_buf.extend(segments);
1573
1574 Arc::new(TestFile {
1575 path: path_buf.as_path().into(),
1576 root_name: WORKTREE_NAME.to_string(),
1577 local_root: Some(PathBuf::from(if cfg!(windows) {
1578 "C:\\absolute\\"
1579 } else {
1580 "/absolute/"
1581 })),
1582 })
1583 };
1584
1585 let test_file = make_test_file(&["src", "test", "file.rs"]);
1586
1587 // Test relative globs
1588 let settings = build_settings(&["*.rs"]);
1589 assert!(!settings.enabled_for_file(&test_file, &cx));
1590 let settings = build_settings(&["*.txt"]);
1591 assert!(settings.enabled_for_file(&test_file, &cx));
1592
1593 // Test absolute globs
1594 let settings = build_settings(&["/absolute/**/*.rs"]);
1595 assert!(!settings.enabled_for_file(&test_file, &cx));
1596 let settings = build_settings(&["/other/**/*.rs"]);
1597 assert!(settings.enabled_for_file(&test_file, &cx));
1598
1599 // Test exact path match relative
1600 let settings = build_settings(&["src/test/file.rs"]);
1601 assert!(!settings.enabled_for_file(&test_file, &cx));
1602 let settings = build_settings(&["src/test/otherfile.rs"]);
1603 assert!(settings.enabled_for_file(&test_file, &cx));
1604
1605 // Test exact path match absolute
1606 let settings = build_settings(&[&format!("/absolute/{}/src/test/file.rs", WORKTREE_NAME)]);
1607 assert!(!settings.enabled_for_file(&test_file, &cx));
1608 let settings = build_settings(&["/other/test/otherfile.rs"]);
1609 assert!(settings.enabled_for_file(&test_file, &cx));
1610
1611 // Test * glob
1612 let settings = build_settings(&["*"]);
1613 assert!(!settings.enabled_for_file(&test_file, &cx));
1614 let settings = build_settings(&["*.txt"]);
1615 assert!(settings.enabled_for_file(&test_file, &cx));
1616
1617 // Test **/* glob
1618 let settings = build_settings(&["**/*"]);
1619 assert!(!settings.enabled_for_file(&test_file, &cx));
1620 let settings = build_settings(&["other/**/*"]);
1621 assert!(settings.enabled_for_file(&test_file, &cx));
1622
1623 // Test directory/** glob
1624 let settings = build_settings(&["src/**"]);
1625 assert!(!settings.enabled_for_file(&test_file, &cx));
1626
1627 let test_file_root: Arc<dyn File> = Arc::new(TestFile {
1628 path: PathBuf::from("file.rs").as_path().into(),
1629 root_name: WORKTREE_NAME.to_string(),
1630 local_root: Some(PathBuf::from("/absolute/")),
1631 });
1632 assert!(settings.enabled_for_file(&test_file_root, &cx));
1633
1634 let settings = build_settings(&["other/**"]);
1635 assert!(settings.enabled_for_file(&test_file, &cx));
1636
1637 // Test **/directory/* glob
1638 let settings = build_settings(&["**/test/*"]);
1639 assert!(!settings.enabled_for_file(&test_file, &cx));
1640 let settings = build_settings(&["**/other/*"]);
1641 assert!(settings.enabled_for_file(&test_file, &cx));
1642
1643 // Test multiple globs
1644 let settings = build_settings(&["*.rs", "*.txt", "src/**"]);
1645 assert!(!settings.enabled_for_file(&test_file, &cx));
1646 let settings = build_settings(&["*.txt", "*.md", "other/**"]);
1647 assert!(settings.enabled_for_file(&test_file, &cx));
1648
1649 // Test dot files
1650 let dot_file = make_test_file(&[".config", "settings.json"]);
1651 let settings = build_settings(&[".*/**"]);
1652 assert!(!settings.enabled_for_file(&dot_file, &cx));
1653
1654 let dot_env_file = make_test_file(&[".env"]);
1655 let settings = build_settings(&[".env"]);
1656 assert!(!settings.enabled_for_file(&dot_env_file, &cx));
1657 }
1658
1659 #[test]
1660 pub fn test_resolve_language_servers() {
1661 fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
1662 names
1663 .iter()
1664 .copied()
1665 .map(|name| LanguageServerName(name.to_string().into()))
1666 .collect::<Vec<_>>()
1667 }
1668
1669 let available_language_servers = language_server_names(&[
1670 "typescript-language-server",
1671 "biome",
1672 "deno",
1673 "eslint",
1674 "tailwind",
1675 ]);
1676
1677 // A value of just `["..."]` is the same as taking all of the available language servers.
1678 assert_eq!(
1679 LanguageSettings::resolve_language_servers(
1680 &[LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()],
1681 &available_language_servers,
1682 ),
1683 available_language_servers
1684 );
1685
1686 // Referencing one of the available language servers will change its order.
1687 assert_eq!(
1688 LanguageSettings::resolve_language_servers(
1689 &[
1690 "biome".into(),
1691 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into(),
1692 "deno".into()
1693 ],
1694 &available_language_servers
1695 ),
1696 language_server_names(&[
1697 "biome",
1698 "typescript-language-server",
1699 "eslint",
1700 "tailwind",
1701 "deno",
1702 ])
1703 );
1704
1705 // Negating an available language server removes it from the list.
1706 assert_eq!(
1707 LanguageSettings::resolve_language_servers(
1708 &[
1709 "deno".into(),
1710 "!typescript-language-server".into(),
1711 "!biome".into(),
1712 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1713 ],
1714 &available_language_servers
1715 ),
1716 language_server_names(&["deno", "eslint", "tailwind"])
1717 );
1718
1719 // Adding a language server not in the list of available language servers adds it to the list.
1720 assert_eq!(
1721 LanguageSettings::resolve_language_servers(
1722 &[
1723 "my-cool-language-server".into(),
1724 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1725 ],
1726 &available_language_servers
1727 ),
1728 language_server_names(&[
1729 "my-cool-language-server",
1730 "typescript-language-server",
1731 "biome",
1732 "deno",
1733 "eslint",
1734 "tailwind",
1735 ])
1736 );
1737 }
1738}