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