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