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