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