language.rs

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