1use std::num::NonZeroU32;
2
3use collections::{HashMap, HashSet};
4use gpui::{Modifiers, SharedString};
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize, de::Error as _};
7use settings_macros::{MergeFrom, with_fallible_options};
8use std::sync::Arc;
9
10use crate::{ExtendingVec, merge_from};
11
12#[with_fallible_options]
13#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
14pub struct AllLanguageSettingsContent {
15 /// The settings for enabling/disabling features.
16 pub features: Option<FeaturesContent>,
17 /// The edit prediction settings.
18 pub edit_predictions: Option<EditPredictionSettingsContent>,
19 /// The default language settings.
20 #[serde(flatten)]
21 pub defaults: LanguageSettingsContent,
22 /// The settings for individual languages.
23 #[serde(default)]
24 pub languages: LanguageToSettingsMap,
25 /// Settings for associating file extensions and filenames
26 /// with languages.
27 pub file_types: Option<HashMap<Arc<str>, ExtendingVec<String>>>,
28}
29
30impl merge_from::MergeFrom for AllLanguageSettingsContent {
31 fn merge_from(&mut self, other: &Self) {
32 self.file_types.merge_from(&other.file_types);
33 self.features.merge_from(&other.features);
34 self.edit_predictions.merge_from(&other.edit_predictions);
35
36 // A user's global settings override the default global settings and
37 // all default language-specific settings.
38 //
39 self.defaults.merge_from(&other.defaults);
40 for language_settings in self.languages.0.values_mut() {
41 language_settings.merge_from(&other.defaults);
42 }
43
44 // A user's language-specific settings override default language-specific settings.
45 for (language_name, user_language_settings) in &other.languages.0 {
46 if let Some(existing) = self.languages.0.get_mut(language_name) {
47 existing.merge_from(&user_language_settings);
48 } else {
49 let mut new_settings = self.defaults.clone();
50 new_settings.merge_from(&user_language_settings);
51
52 self.languages.0.insert(language_name.clone(), new_settings);
53 }
54 }
55 }
56}
57
58/// The settings for enabling/disabling features.
59#[with_fallible_options]
60#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
61#[serde(rename_all = "snake_case")]
62pub struct FeaturesContent {
63 /// Determines which edit prediction provider to use.
64 pub edit_prediction_provider: Option<EditPredictionProvider>,
65 /// Enables the experimental edit prediction context retrieval system.
66 pub experimental_edit_prediction_context_retrieval: Option<bool>,
67}
68
69/// The provider that supplies edit predictions.
70#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, JsonSchema, MergeFrom)]
71#[serde(rename_all = "snake_case")]
72pub enum EditPredictionProvider {
73 None,
74 #[default]
75 Copilot,
76 Supermaven,
77 Zed,
78 Codestral,
79 Experimental(&'static str),
80}
81
82pub const EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME: &str = "sweep";
83pub const EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME: &str = "zeta2";
84pub const EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME: &str = "mercury";
85
86impl<'de> Deserialize<'de> for EditPredictionProvider {
87 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
88 where
89 D: serde::Deserializer<'de>,
90 {
91 #[derive(Deserialize)]
92 #[serde(rename_all = "snake_case")]
93 pub enum Content {
94 None,
95 Copilot,
96 Supermaven,
97 Zed,
98 Codestral,
99 Experimental(String),
100 }
101
102 Ok(match Content::deserialize(deserializer)? {
103 Content::None => EditPredictionProvider::None,
104 Content::Copilot => EditPredictionProvider::Copilot,
105 Content::Supermaven => EditPredictionProvider::Supermaven,
106 Content::Zed => EditPredictionProvider::Zed,
107 Content::Codestral => EditPredictionProvider::Codestral,
108 Content::Experimental(name)
109 if name == EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME =>
110 {
111 EditPredictionProvider::Experimental(
112 EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
113 )
114 }
115 Content::Experimental(name)
116 if name == EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME =>
117 {
118 EditPredictionProvider::Experimental(
119 EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
120 )
121 }
122 Content::Experimental(name)
123 if name == EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME =>
124 {
125 EditPredictionProvider::Experimental(
126 EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
127 )
128 }
129 Content::Experimental(name) => {
130 return Err(D::Error::custom(format!(
131 "Unknown experimental edit prediction provider: {}",
132 name
133 )));
134 }
135 })
136 }
137}
138
139impl EditPredictionProvider {
140 pub fn is_zed(&self) -> bool {
141 match self {
142 EditPredictionProvider::Zed => true,
143 EditPredictionProvider::None
144 | EditPredictionProvider::Copilot
145 | EditPredictionProvider::Supermaven
146 | EditPredictionProvider::Codestral
147 | EditPredictionProvider::Experimental(_) => false,
148 }
149 }
150}
151
152/// The contents of the edit prediction settings.
153#[with_fallible_options]
154#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
155pub struct EditPredictionSettingsContent {
156 /// A list of globs representing files that edit predictions should be disabled for.
157 /// This list adds to a pre-existing, sensible default set of globs.
158 /// Any additional ones you add are combined with them.
159 pub disabled_globs: Option<Vec<String>>,
160 /// The mode used to display edit predictions in the buffer.
161 /// Provider support required.
162 pub mode: Option<EditPredictionsMode>,
163 /// Settings specific to GitHub Copilot.
164 pub copilot: Option<CopilotSettingsContent>,
165 /// Settings specific to Codestral.
166 pub codestral: Option<CodestralSettingsContent>,
167 /// Whether edit predictions are enabled in the assistant prompt editor.
168 /// This has no effect if globally disabled.
169 pub enabled_in_text_threads: Option<bool>,
170}
171
172#[with_fallible_options]
173#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
174pub struct CopilotSettingsContent {
175 /// HTTP/HTTPS proxy to use for Copilot.
176 ///
177 /// Default: none
178 pub proxy: Option<String>,
179 /// Disable certificate verification for the proxy (not recommended).
180 ///
181 /// Default: false
182 pub proxy_no_verify: Option<bool>,
183 /// Enterprise URI for Copilot.
184 ///
185 /// Default: none
186 pub enterprise_uri: Option<String>,
187}
188
189#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
190pub struct CodestralSettingsContent {
191 /// Model to use for completions.
192 ///
193 /// Default: "codestral-latest"
194 #[serde(default)]
195 pub model: Option<String>,
196 /// Maximum tokens to generate.
197 ///
198 /// Default: 150
199 #[serde(default)]
200 pub max_tokens: Option<u32>,
201 /// Api URL to use for completions.
202 ///
203 /// Default: "https://codestral.mistral.ai"
204 #[serde(default)]
205 pub api_url: Option<String>,
206}
207
208/// The mode in which edit predictions should be displayed.
209#[derive(
210 Copy,
211 Clone,
212 Debug,
213 Default,
214 Eq,
215 PartialEq,
216 Serialize,
217 Deserialize,
218 JsonSchema,
219 MergeFrom,
220 strum::VariantArray,
221 strum::VariantNames,
222)]
223#[serde(rename_all = "snake_case")]
224pub enum EditPredictionsMode {
225 /// If provider supports it, display inline when holding modifier key (e.g., alt).
226 /// Otherwise, eager preview is used.
227 #[serde(alias = "auto")]
228 Subtle,
229 /// Display inline when there are no language server completions available.
230 #[default]
231 #[serde(alias = "eager_preview")]
232 Eager,
233}
234
235/// Controls the soft-wrapping behavior in the editor.
236#[derive(
237 Copy,
238 Clone,
239 Debug,
240 Serialize,
241 Deserialize,
242 PartialEq,
243 Eq,
244 JsonSchema,
245 MergeFrom,
246 strum::VariantArray,
247 strum::VariantNames,
248)]
249#[serde(rename_all = "snake_case")]
250pub enum SoftWrap {
251 /// Prefer a single line generally, unless an overly long line is encountered.
252 None,
253 /// Deprecated: use None instead. Left to avoid breaking existing users' configs.
254 /// Prefer a single line generally, unless an overly long line is encountered.
255 PreferLine,
256 /// Soft wrap lines that exceed the editor width.
257 EditorWidth,
258 /// Soft wrap lines at the preferred line length.
259 PreferredLineLength,
260 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
261 Bounded,
262}
263
264/// The settings for a particular language.
265#[with_fallible_options]
266#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
267pub struct LanguageSettingsContent {
268 /// How many columns a tab should occupy.
269 ///
270 /// Default: 4
271 #[schemars(range(min = 1, max = 128))]
272 pub tab_size: Option<NonZeroU32>,
273 /// Whether to indent lines using tab characters, as opposed to multiple
274 /// spaces.
275 ///
276 /// Default: false
277 pub hard_tabs: Option<bool>,
278 /// How to soft-wrap long lines of text.
279 ///
280 /// Default: none
281 pub soft_wrap: Option<SoftWrap>,
282 /// The column at which to soft-wrap lines, for buffers where soft-wrap
283 /// is enabled.
284 ///
285 /// Default: 80
286 pub preferred_line_length: Option<u32>,
287 /// Whether to show wrap guides in the editor. Setting this to true will
288 /// show a guide at the 'preferred_line_length' value if softwrap is set to
289 /// 'preferred_line_length', and will show any additional guides as specified
290 /// by the 'wrap_guides' setting.
291 ///
292 /// Default: true
293 pub show_wrap_guides: Option<bool>,
294 /// Character counts at which to show wrap guides in the editor.
295 ///
296 /// Default: []
297 pub wrap_guides: Option<Vec<usize>>,
298 /// Indent guide related settings.
299 pub indent_guides: Option<IndentGuideSettingsContent>,
300 /// Whether or not to perform a buffer format before saving.
301 ///
302 /// Default: on
303 pub format_on_save: Option<FormatOnSave>,
304 /// Whether or not to remove any trailing whitespace from lines of a buffer
305 /// before saving it.
306 ///
307 /// Default: true
308 pub remove_trailing_whitespace_on_save: Option<bool>,
309 /// Whether or not to ensure there's a single newline at the end of a buffer
310 /// when saving it.
311 ///
312 /// Default: true
313 pub ensure_final_newline_on_save: Option<bool>,
314 /// How to perform a buffer format.
315 ///
316 /// Default: auto
317 pub formatter: Option<FormatterList>,
318 /// Zed's Prettier integration settings.
319 /// Allows to enable/disable formatting with Prettier
320 /// and configure default Prettier, used when no project-level Prettier installation is found.
321 ///
322 /// Default: off
323 pub prettier: Option<PrettierSettingsContent>,
324 /// Whether to automatically close JSX tags.
325 pub jsx_tag_auto_close: Option<JsxTagAutoCloseSettingsContent>,
326 /// Whether to use language servers to provide code intelligence.
327 ///
328 /// Default: true
329 pub enable_language_server: Option<bool>,
330 /// The list of language servers to use (or disable) for this language.
331 ///
332 /// This array should consist of language server IDs, as well as the following
333 /// special tokens:
334 /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
335 /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
336 ///
337 /// Default: ["..."]
338 pub language_servers: Option<Vec<String>>,
339 /// Controls where the `editor::Rewrap` action is allowed for this language.
340 ///
341 /// Note: This setting has no effect in Vim mode, as rewrap is already
342 /// allowed everywhere.
343 ///
344 /// Default: "in_comments"
345 pub allow_rewrap: Option<RewrapBehavior>,
346 /// Controls whether edit predictions are shown immediately (true)
347 /// or manually by triggering `editor::ShowEditPrediction` (false).
348 ///
349 /// Default: true
350 pub show_edit_predictions: Option<bool>,
351 /// Controls whether edit predictions are shown in the given language
352 /// scopes.
353 ///
354 /// Example: ["string", "comment"]
355 ///
356 /// Default: []
357 pub edit_predictions_disabled_in: Option<Vec<String>>,
358 /// Whether to show tabs and spaces in the editor.
359 pub show_whitespaces: Option<ShowWhitespaceSetting>,
360 /// Visible characters used to render whitespace when show_whitespaces is enabled.
361 ///
362 /// Default: "•" for spaces, "→" for tabs.
363 pub whitespace_map: Option<WhitespaceMapContent>,
364 /// Whether to start a new line with a comment when a previous line is a comment as well.
365 ///
366 /// Default: true
367 pub extend_comment_on_newline: Option<bool>,
368 /// Inlay hint related settings.
369 pub inlay_hints: Option<InlayHintSettingsContent>,
370 /// Whether to automatically type closing characters for you. For example,
371 /// when you type '(', Zed will automatically add a closing ')' at the correct position.
372 ///
373 /// Default: true
374 pub use_autoclose: Option<bool>,
375 /// Whether to automatically surround text with characters for you. For example,
376 /// when you select text and type '(', Zed will automatically surround text with ().
377 ///
378 /// Default: true
379 pub use_auto_surround: Option<bool>,
380 /// Controls how the editor handles the autoclosed characters.
381 /// When set to `false`(default), skipping over and auto-removing of the closing characters
382 /// happen only for auto-inserted characters.
383 /// Otherwise(when `true`), the closing characters are always skipped over and auto-removed
384 /// no matter how they were inserted.
385 ///
386 /// Default: false
387 pub always_treat_brackets_as_autoclosed: Option<bool>,
388 /// Whether to use additional LSP queries to format (and amend) the code after
389 /// every "trigger" symbol input, defined by LSP server capabilities.
390 ///
391 /// Default: true
392 pub use_on_type_format: Option<bool>,
393 /// Which code actions to run on save before the formatter.
394 /// These are not run if formatting is off.
395 ///
396 /// Default: {} (or {"source.organizeImports": true} for Go).
397 pub code_actions_on_format: Option<HashMap<String, bool>>,
398 /// Whether to perform linked edits of associated ranges, if the language server supports it.
399 /// For example, when editing opening <html> tag, the contents of the closing </html> tag will be edited as well.
400 ///
401 /// Default: true
402 pub linked_edits: Option<bool>,
403 /// Whether indentation should be adjusted based on the context whilst typing.
404 ///
405 /// Default: true
406 pub auto_indent: Option<bool>,
407 /// Whether indentation of pasted content should be adjusted based on the context.
408 ///
409 /// Default: true
410 pub auto_indent_on_paste: Option<bool>,
411 /// Task configuration for this language.
412 ///
413 /// Default: {}
414 pub tasks: Option<LanguageTaskSettingsContent>,
415 /// Whether to pop the completions menu while typing in an editor without
416 /// explicitly requesting it.
417 ///
418 /// Default: true
419 pub show_completions_on_input: Option<bool>,
420 /// Whether to display inline and alongside documentation for items in the
421 /// completions menu.
422 ///
423 /// Default: true
424 pub show_completion_documentation: Option<bool>,
425 /// Controls how completions are processed for this language.
426 pub completions: Option<CompletionSettingsContent>,
427 /// Preferred debuggers for this language.
428 ///
429 /// Default: []
430 pub debuggers: Option<Vec<String>>,
431 /// Whether to enable word diff highlighting in the editor.
432 ///
433 /// When enabled, changed words within modified lines are highlighted
434 /// to show exactly what changed.
435 ///
436 /// Default: true
437 pub word_diff_enabled: Option<bool>,
438 /// Whether to use tree-sitter bracket queries to detect and colorize the brackets in the editor.
439 ///
440 /// Default: false
441 pub colorize_brackets: Option<bool>,
442}
443
444/// Controls how whitespace should be displayedin the editor.
445#[derive(
446 Copy,
447 Clone,
448 Debug,
449 Serialize,
450 Deserialize,
451 PartialEq,
452 Eq,
453 JsonSchema,
454 MergeFrom,
455 strum::VariantArray,
456 strum::VariantNames,
457)]
458#[serde(rename_all = "snake_case")]
459pub enum ShowWhitespaceSetting {
460 /// Draw whitespace only for the selected text.
461 Selection,
462 /// Do not draw any tabs or spaces.
463 None,
464 /// Draw all invisible symbols.
465 All,
466 /// Draw whitespaces at boundaries only.
467 ///
468 /// For a whitespace to be on a boundary, any of the following conditions need to be met:
469 /// - It is a tab
470 /// - It is adjacent to an edge (start or end)
471 /// - It is adjacent to a whitespace (left or right)
472 Boundary,
473 /// Draw whitespaces only after non-whitespace characters.
474 Trailing,
475}
476
477#[with_fallible_options]
478#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
479pub struct WhitespaceMapContent {
480 pub space: Option<char>,
481 pub tab: Option<char>,
482}
483
484/// The behavior of `editor::Rewrap`.
485#[derive(
486 Debug,
487 PartialEq,
488 Clone,
489 Copy,
490 Default,
491 Serialize,
492 Deserialize,
493 JsonSchema,
494 MergeFrom,
495 strum::VariantArray,
496 strum::VariantNames,
497)]
498#[serde(rename_all = "snake_case")]
499pub enum RewrapBehavior {
500 /// Only rewrap within comments.
501 #[default]
502 InComments,
503 /// Only rewrap within the current selection(s).
504 InSelections,
505 /// Allow rewrapping anywhere.
506 Anywhere,
507}
508
509#[with_fallible_options]
510#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
511pub struct JsxTagAutoCloseSettingsContent {
512 /// Enables or disables auto-closing of JSX tags.
513 pub enabled: Option<bool>,
514}
515
516/// The settings for inlay hints.
517#[with_fallible_options]
518#[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq, Eq)]
519pub struct InlayHintSettingsContent {
520 /// Global switch to toggle hints on and off.
521 ///
522 /// Default: false
523 pub enabled: Option<bool>,
524 /// Global switch to toggle inline values on and off when debugging.
525 ///
526 /// Default: true
527 pub show_value_hints: Option<bool>,
528 /// Whether type hints should be shown.
529 ///
530 /// Default: true
531 pub show_type_hints: Option<bool>,
532 /// Whether parameter hints should be shown.
533 ///
534 /// Default: true
535 pub show_parameter_hints: Option<bool>,
536 /// Whether other hints should be shown.
537 ///
538 /// Default: true
539 pub show_other_hints: Option<bool>,
540 /// Whether to show a background for inlay hints.
541 ///
542 /// If set to `true`, the background will use the `hint.background` color
543 /// from the current theme.
544 ///
545 /// Default: false
546 pub show_background: Option<bool>,
547 /// Whether or not to debounce inlay hints updates after buffer edits.
548 ///
549 /// Set to 0 to disable debouncing.
550 ///
551 /// Default: 700
552 pub edit_debounce_ms: Option<u64>,
553 /// Whether or not to debounce inlay hints updates after buffer scrolls.
554 ///
555 /// Set to 0 to disable debouncing.
556 ///
557 /// Default: 50
558 pub scroll_debounce_ms: Option<u64>,
559 /// Toggles inlay hints (hides or shows) when the user presses the modifiers specified.
560 /// If only a subset of the modifiers specified is pressed, hints are not toggled.
561 /// If no modifiers are specified, this is equivalent to `null`.
562 ///
563 /// Default: null
564 pub toggle_on_modifiers_press: Option<Modifiers>,
565}
566
567/// The kind of an inlay hint.
568#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
569pub enum InlayHintKind {
570 /// An inlay hint for a type.
571 Type,
572 /// An inlay hint for a parameter.
573 Parameter,
574}
575
576impl InlayHintKind {
577 /// Returns the [`InlayHintKind`]fromthe given name.
578 ///
579 /// Returns `None` if `name` does not match any of the expected
580 /// string representations.
581 pub fn from_name(name: &str) -> Option<Self> {
582 match name {
583 "type" => Some(InlayHintKind::Type),
584 "parameter" => Some(InlayHintKind::Parameter),
585 _ => None,
586 }
587 }
588
589 /// Returns the name of this [`InlayHintKind`].
590 pub fn name(&self) -> &'static str {
591 match self {
592 InlayHintKind::Type => "type",
593 InlayHintKind::Parameter => "parameter",
594 }
595 }
596}
597
598/// Controls how completions are processed for this language.
599#[with_fallible_options]
600#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom, Default)]
601#[serde(rename_all = "snake_case")]
602pub struct CompletionSettingsContent {
603 /// Controls how words are completed.
604 /// For large documents, not all words may be fetched for completion.
605 ///
606 /// Default: `fallback`
607 pub words: Option<WordsCompletionMode>,
608 /// How many characters has to be in the completions query to automatically show the words-based completions.
609 /// Before that value, it's still possible to trigger the words-based completion manually with the corresponding editor command.
610 ///
611 /// Default: 3
612 pub words_min_length: Option<u32>,
613 /// Whether to fetch LSP completions or not.
614 ///
615 /// Default: true
616 pub lsp: Option<bool>,
617 /// When fetching LSP completions, determines how long to wait for a response of a particular server.
618 /// When set to 0, waits indefinitely.
619 ///
620 /// Default: 0
621 pub lsp_fetch_timeout_ms: Option<u64>,
622 /// Controls how LSP completions are inserted.
623 ///
624 /// Default: "replace_suffix"
625 pub lsp_insert_mode: Option<LspInsertMode>,
626}
627
628#[derive(
629 Copy,
630 Clone,
631 Debug,
632 Serialize,
633 Deserialize,
634 PartialEq,
635 Eq,
636 JsonSchema,
637 MergeFrom,
638 strum::VariantArray,
639 strum::VariantNames,
640)]
641#[serde(rename_all = "snake_case")]
642pub enum LspInsertMode {
643 /// Replaces text before the cursor, using the `insert` range described in the LSP specification.
644 Insert,
645 /// Replaces text before and after the cursor, using the `replace` range described in the LSP specification.
646 Replace,
647 /// Behaves like `"replace"` if the text that would be replaced is a subsequence of the completion text,
648 /// and like `"insert"` otherwise.
649 ReplaceSubsequence,
650 /// Behaves like `"replace"` if the text after the cursor is a suffix of the completion, and like
651 /// `"insert"` otherwise.
652 ReplaceSuffix,
653}
654
655/// Controls how document's words are completed.
656#[derive(
657 Copy,
658 Clone,
659 Debug,
660 Serialize,
661 Deserialize,
662 PartialEq,
663 Eq,
664 JsonSchema,
665 MergeFrom,
666 strum::VariantArray,
667 strum::VariantNames,
668)]
669#[serde(rename_all = "snake_case")]
670pub enum WordsCompletionMode {
671 /// Always fetch document's words for completions along with LSP completions.
672 Enabled,
673 /// Only if LSP response errors or times out,
674 /// use document's words to show completions.
675 Fallback,
676 /// Never fetch or complete document's words for completions.
677 /// (Word-based completions can still be queried via a separate action)
678 Disabled,
679}
680
681/// Allows to enable/disable formatting with Prettier
682/// and configure default Prettier, used when no project-level Prettier installation is found.
683/// Prettier formatting is disabled by default.
684#[with_fallible_options]
685#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
686pub struct PrettierSettingsContent {
687 /// Enables or disables formatting with Prettier for a given language.
688 pub allowed: Option<bool>,
689
690 /// Forces Prettier integration to use a specific parser name when formatting files with the language.
691 pub parser: Option<String>,
692
693 /// Forces Prettier integration to use specific plugins when formatting files with the language.
694 /// The default Prettier will be installed with these plugins.
695 pub plugins: Option<HashSet<String>>,
696
697 /// Default Prettier options, in the format as in package.json section for Prettier.
698 /// If project installs Prettier via its package.json, these options will be ignored.
699 #[serde(flatten)]
700 pub options: Option<HashMap<String, serde_json::Value>>,
701}
702
703/// TODO: this should just be a bool
704/// Controls the behavior of formatting files when they are saved.
705#[derive(
706 Debug,
707 Clone,
708 Copy,
709 PartialEq,
710 Eq,
711 Serialize,
712 Deserialize,
713 JsonSchema,
714 MergeFrom,
715 strum::VariantArray,
716 strum::VariantNames,
717)]
718#[serde(rename_all = "lowercase")]
719pub enum FormatOnSave {
720 /// Files should be formatted on save.
721 On,
722 /// Files should not be formatted on save.
723 Off,
724}
725
726/// Controls which formatters should be used when formatting code.
727#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
728#[serde(untagged)]
729pub enum FormatterList {
730 Single(Formatter),
731 Vec(Vec<Formatter>),
732}
733
734impl Default for FormatterList {
735 fn default() -> Self {
736 Self::Single(Formatter::default())
737 }
738}
739
740impl AsRef<[Formatter]> for FormatterList {
741 fn as_ref(&self) -> &[Formatter] {
742 match &self {
743 Self::Single(single) => std::slice::from_ref(single),
744 Self::Vec(v) => v,
745 }
746 }
747}
748
749/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
750#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
751#[serde(rename_all = "snake_case")]
752pub enum Formatter {
753 /// Format files using Zed's Prettier integration (if applicable),
754 /// or falling back to formatting via language server.
755 #[default]
756 Auto,
757 /// Format code using Zed's Prettier integration.
758 Prettier,
759 /// Format code using an external command.
760 External {
761 /// The external program to run.
762 command: Arc<str>,
763 /// The arguments to pass to the program.
764 arguments: Option<Arc<[String]>>,
765 },
766 /// Files should be formatted using a code action executed by language servers.
767 CodeAction(String),
768 /// Format code using a language server.
769 #[serde(untagged)]
770 LanguageServer(LanguageServerFormatterSpecifier),
771}
772
773#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
774#[serde(
775 rename_all = "snake_case",
776 // allow specifying language servers as "language_server" or {"language_server": {"name": ...}}
777 from = "LanguageServerVariantContent",
778 into = "LanguageServerVariantContent"
779)]
780pub enum LanguageServerFormatterSpecifier {
781 Specific {
782 name: String,
783 },
784 #[default]
785 Current,
786}
787
788impl From<LanguageServerVariantContent> for LanguageServerFormatterSpecifier {
789 fn from(value: LanguageServerVariantContent) -> Self {
790 match value {
791 LanguageServerVariantContent::Specific {
792 language_server: LanguageServerSpecifierContent { name: Some(name) },
793 } => Self::Specific { name },
794 _ => Self::Current,
795 }
796 }
797}
798
799impl From<LanguageServerFormatterSpecifier> for LanguageServerVariantContent {
800 fn from(value: LanguageServerFormatterSpecifier) -> Self {
801 match value {
802 LanguageServerFormatterSpecifier::Specific { name } => Self::Specific {
803 language_server: LanguageServerSpecifierContent { name: Some(name) },
804 },
805 LanguageServerFormatterSpecifier::Current => {
806 Self::Current(CurrentLanguageServerContent::LanguageServer)
807 }
808 }
809 }
810}
811
812#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
813#[serde(rename_all = "snake_case", untagged)]
814enum LanguageServerVariantContent {
815 /// Format code using a specific language server.
816 Specific {
817 language_server: LanguageServerSpecifierContent,
818 },
819 /// Format code using the current language server.
820 Current(CurrentLanguageServerContent),
821}
822
823#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
824#[serde(rename_all = "snake_case")]
825enum CurrentLanguageServerContent {
826 #[default]
827 LanguageServer,
828}
829
830#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
831#[serde(rename_all = "snake_case")]
832struct LanguageServerSpecifierContent {
833 /// The name of the language server to format with
834 name: Option<String>,
835}
836
837/// The settings for indent guides.
838#[with_fallible_options]
839#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
840pub struct IndentGuideSettingsContent {
841 /// Whether to display indent guides in the editor.
842 ///
843 /// Default: true
844 pub enabled: Option<bool>,
845 /// The width of the indent guides in pixels, between 1 and 10.
846 ///
847 /// Default: 1
848 pub line_width: Option<u32>,
849 /// The width of the active indent guide in pixels, between 1 and 10.
850 ///
851 /// Default: 1
852 pub active_line_width: Option<u32>,
853 /// Determines how indent guides are colored.
854 ///
855 /// Default: Fixed
856 pub coloring: Option<IndentGuideColoring>,
857 /// Determines how indent guide backgrounds are colored.
858 ///
859 /// Default: Disabled
860 pub background_coloring: Option<IndentGuideBackgroundColoring>,
861}
862
863/// The task settings for a particular language.
864#[with_fallible_options]
865#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize, JsonSchema, MergeFrom)]
866pub struct LanguageTaskSettingsContent {
867 /// Extra task variables to set for a particular language.
868 pub variables: Option<HashMap<String, String>>,
869 pub enabled: Option<bool>,
870 /// Use LSP tasks over Zed language extension ones.
871 /// If no LSP tasks are returned due to error/timeout or regular execution,
872 /// Zed language extension tasks will be used instead.
873 ///
874 /// Other Zed tasks will still be shown:
875 /// * Zed task from either of the task config file
876 /// * Zed task from history (e.g. one-off task was spawned before)
877 pub prefer_lsp: Option<bool>,
878}
879
880/// Map from language name to settings.
881#[with_fallible_options]
882#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
883pub struct LanguageToSettingsMap(pub HashMap<SharedString, LanguageSettingsContent>);
884
885/// Determines how indent guides are colored.
886#[derive(
887 Default,
888 Debug,
889 Copy,
890 Clone,
891 PartialEq,
892 Eq,
893 Serialize,
894 Deserialize,
895 JsonSchema,
896 MergeFrom,
897 strum::VariantArray,
898 strum::VariantNames,
899)]
900#[serde(rename_all = "snake_case")]
901pub enum IndentGuideColoring {
902 /// Do not render any lines for indent guides.
903 Disabled,
904 /// Use the same color for all indentation levels.
905 #[default]
906 Fixed,
907 /// Use a different color for each indentation level.
908 IndentAware,
909}
910
911/// Determines how indent guide backgrounds are colored.
912#[derive(
913 Default,
914 Debug,
915 Copy,
916 Clone,
917 PartialEq,
918 Eq,
919 Serialize,
920 Deserialize,
921 JsonSchema,
922 MergeFrom,
923 strum::VariantArray,
924 strum::VariantNames,
925)]
926#[serde(rename_all = "snake_case")]
927pub enum IndentGuideBackgroundColoring {
928 /// Do not render any background for indent guides.
929 #[default]
930 Disabled,
931 /// Use a different color for each indentation level.
932 IndentAware,
933}
934
935#[cfg(test)]
936mod test {
937
938 use crate::{ParseStatus, fallible_options};
939
940 use super::*;
941
942 #[test]
943 fn test_formatter_deserialization() {
944 let raw_auto = "{\"formatter\": \"auto\"}";
945 let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
946 assert_eq!(
947 settings.formatter,
948 Some(FormatterList::Single(Formatter::Auto))
949 );
950 let raw = "{\"formatter\": \"language_server\"}";
951 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
952 assert_eq!(
953 settings.formatter,
954 Some(FormatterList::Single(Formatter::LanguageServer(
955 LanguageServerFormatterSpecifier::Current
956 )))
957 );
958
959 let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
960 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
961 assert_eq!(
962 settings.formatter,
963 Some(FormatterList::Vec(vec![Formatter::LanguageServer(
964 LanguageServerFormatterSpecifier::Current
965 )]))
966 );
967 let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"language_server\", \"prettier\"]}";
968 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
969 assert_eq!(
970 settings.formatter,
971 Some(FormatterList::Vec(vec![
972 Formatter::LanguageServer(LanguageServerFormatterSpecifier::Current),
973 Formatter::LanguageServer(LanguageServerFormatterSpecifier::Current),
974 Formatter::Prettier
975 ]))
976 );
977
978 let raw = "{\"formatter\": [{\"language_server\": {\"name\": \"ruff\"}}, \"prettier\"]}";
979 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
980 assert_eq!(
981 settings.formatter,
982 Some(FormatterList::Vec(vec![
983 Formatter::LanguageServer(LanguageServerFormatterSpecifier::Specific {
984 name: "ruff".to_string()
985 }),
986 Formatter::Prettier
987 ]))
988 );
989
990 assert_eq!(
991 serde_json::to_string(&LanguageServerFormatterSpecifier::Current).unwrap(),
992 "\"language_server\"",
993 );
994 }
995
996 #[test]
997 fn test_formatter_deserialization_invalid() {
998 let raw_auto = "{\"formatter\": {}}";
999 let (_, result) = fallible_options::parse_json::<LanguageSettingsContent>(raw_auto);
1000 assert!(matches!(result, ParseStatus::Failed { .. }));
1001 }
1002
1003 #[test]
1004 fn test_prettier_options() {
1005 let raw_prettier = r#"{"allowed": false, "tabWidth": 4, "semi": false}"#;
1006 let result = serde_json::from_str::<PrettierSettingsContent>(raw_prettier)
1007 .expect("Failed to parse prettier options");
1008 assert!(
1009 result
1010 .options
1011 .as_ref()
1012 .expect("options were flattened")
1013 .contains_key("semi")
1014 );
1015 assert!(
1016 result
1017 .options
1018 .as_ref()
1019 .expect("options were flattened")
1020 .contains_key("tabWidth")
1021 );
1022 }
1023}