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