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