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(Debug, PartialEq, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
389#[serde(rename_all = "snake_case")]
390pub enum RewrapBehavior {
391    /// Only rewrap within comments.
392    #[default]
393    InComments,
394    /// Only rewrap within the current selection(s).
395    InSelections,
396    /// Allow rewrapping anywhere.
397    Anywhere,
398}
399
400#[skip_serializing_none]
401#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
402pub struct JsxTagAutoCloseSettingsContent {
403    /// Enables or disables auto-closing of JSX tags.
404    pub enabled: Option<bool>,
405}
406
407/// The settings for inlay hints.
408#[skip_serializing_none]
409#[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq, Eq)]
410pub struct InlayHintSettingsContent {
411    /// Global switch to toggle hints on and off.
412    ///
413    /// Default: false
414    pub enabled: Option<bool>,
415    /// Global switch to toggle inline values on and off when debugging.
416    ///
417    /// Default: true
418    pub show_value_hints: Option<bool>,
419    /// Whether type hints should be shown.
420    ///
421    /// Default: true
422    pub show_type_hints: Option<bool>,
423    /// Whether parameter hints should be shown.
424    ///
425    /// Default: true
426    pub show_parameter_hints: Option<bool>,
427    /// Whether other hints should be shown.
428    ///
429    /// Default: true
430    pub show_other_hints: Option<bool>,
431    /// Whether to show a background for inlay hints.
432    ///
433    /// If set to `true`, the background will use the `hint.background` color
434    /// from the current theme.
435    ///
436    /// Default: false
437    pub show_background: Option<bool>,
438    /// Whether or not to debounce inlay hints updates after buffer edits.
439    ///
440    /// Set to 0 to disable debouncing.
441    ///
442    /// Default: 700
443    pub edit_debounce_ms: Option<u64>,
444    /// Whether or not to debounce inlay hints updates after buffer scrolls.
445    ///
446    /// Set to 0 to disable debouncing.
447    ///
448    /// Default: 50
449    pub scroll_debounce_ms: Option<u64>,
450    /// Toggles inlay hints (hides or shows) when the user presses the modifiers specified.
451    /// If only a subset of the modifiers specified is pressed, hints are not toggled.
452    /// If no modifiers are specified, this is equivalent to `null`.
453    ///
454    /// Default: null
455    pub toggle_on_modifiers_press: Option<Modifiers>,
456}
457
458/// The kind of an inlay hint.
459#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
460pub enum InlayHintKind {
461    /// An inlay hint for a type.
462    Type,
463    /// An inlay hint for a parameter.
464    Parameter,
465}
466
467impl InlayHintKind {
468    /// Returns the [`InlayHintKind`]fromthe given name.
469    ///
470    /// Returns `None` if `name` does not match any of the expected
471    /// string representations.
472    pub fn from_name(name: &str) -> Option<Self> {
473        match name {
474            "type" => Some(InlayHintKind::Type),
475            "parameter" => Some(InlayHintKind::Parameter),
476            _ => None,
477        }
478    }
479
480    /// Returns the name of this [`InlayHintKind`].
481    pub fn name(&self) -> &'static str {
482        match self {
483            InlayHintKind::Type => "type",
484            InlayHintKind::Parameter => "parameter",
485        }
486    }
487}
488
489/// Controls how completions are processed for this language.
490#[skip_serializing_none]
491#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom, Default)]
492#[serde(rename_all = "snake_case")]
493pub struct CompletionSettingsContent {
494    /// Controls how words are completed.
495    /// For large documents, not all words may be fetched for completion.
496    ///
497    /// Default: `fallback`
498    pub words: Option<WordsCompletionMode>,
499    /// How many characters has to be in the completions query to automatically show the words-based completions.
500    /// Before that value, it's still possible to trigger the words-based completion manually with the corresponding editor command.
501    ///
502    /// Default: 3
503    pub words_min_length: Option<usize>,
504    /// Whether to fetch LSP completions or not.
505    ///
506    /// Default: true
507    pub lsp: Option<bool>,
508    /// When fetching LSP completions, determines how long to wait for a response of a particular server.
509    /// When set to 0, waits indefinitely.
510    ///
511    /// Default: 0
512    pub lsp_fetch_timeout_ms: Option<u64>,
513    /// Controls how LSP completions are inserted.
514    ///
515    /// Default: "replace_suffix"
516    pub lsp_insert_mode: Option<LspInsertMode>,
517}
518
519#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
520#[serde(rename_all = "snake_case")]
521pub enum LspInsertMode {
522    /// Replaces text before the cursor, using the `insert` range described in the LSP specification.
523    Insert,
524    /// Replaces text before and after the cursor, using the `replace` range described in the LSP specification.
525    Replace,
526    /// Behaves like `"replace"` if the text that would be replaced is a subsequence of the completion text,
527    /// and like `"insert"` otherwise.
528    ReplaceSubsequence,
529    /// Behaves like `"replace"` if the text after the cursor is a suffix of the completion, and like
530    /// `"insert"` otherwise.
531    ReplaceSuffix,
532}
533
534/// Controls how document's words are completed.
535#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
536#[serde(rename_all = "snake_case")]
537pub enum WordsCompletionMode {
538    /// Always fetch document's words for completions along with LSP completions.
539    Enabled,
540    /// Only if LSP response errors or times out,
541    /// use document's words to show completions.
542    Fallback,
543    /// Never fetch or complete document's words for completions.
544    /// (Word-based completions can still be queried via a separate action)
545    Disabled,
546}
547
548/// Allows to enable/disable formatting with Prettier
549/// and configure default Prettier, used when no project-level Prettier installation is found.
550/// Prettier formatting is disabled by default.
551#[skip_serializing_none]
552#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
553pub struct PrettierSettingsContent {
554    /// Enables or disables formatting with Prettier for a given language.
555    pub allowed: Option<bool>,
556
557    /// Forces Prettier integration to use a specific parser name when formatting files with the language.
558    pub parser: Option<String>,
559
560    /// Forces Prettier integration to use specific plugins when formatting files with the language.
561    /// The default Prettier will be installed with these plugins.
562    #[serde(default)]
563    pub plugins: HashSet<String>,
564
565    /// Default Prettier options, in the format as in package.json section for Prettier.
566    /// If project installs Prettier via its package.json, these options will be ignored.
567    #[serde(flatten)]
568    pub options: HashMap<String, serde_json::Value>,
569}
570
571/// Controls the behavior of formatting files when they are saved.
572#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
573#[serde(rename_all = "lowercase")]
574pub enum FormatOnSave {
575    /// Files should be formatted on save.
576    On,
577    /// Files should not be formatted on save.
578    Off,
579}
580
581/// Controls which formatter should be used when formatting code.
582#[derive(Clone, Debug, Default, PartialEq, Eq, MergeFrom)]
583pub enum SelectedFormatter {
584    /// Format files using Zed's Prettier integration (if applicable),
585    /// or falling back to formatting via language server.
586    #[default]
587    Auto,
588    List(FormatterList),
589}
590
591impl JsonSchema for SelectedFormatter {
592    fn schema_name() -> Cow<'static, str> {
593        "Formatter".into()
594    }
595
596    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
597        let formatter_schema = Formatter::json_schema(generator);
598
599        json_schema!({
600            "oneOf": [
601                {
602                    "type": "array",
603                    "items": formatter_schema
604                },
605                {
606                    "type": "string",
607                    "enum": ["auto", "language_server"]
608                },
609                formatter_schema
610            ]
611        })
612    }
613}
614
615impl Serialize for SelectedFormatter {
616    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
617    where
618        S: serde::Serializer,
619    {
620        match self {
621            SelectedFormatter::Auto => serializer.serialize_str("auto"),
622            SelectedFormatter::List(list) => list.serialize(serializer),
623        }
624    }
625}
626
627impl<'de> Deserialize<'de> for SelectedFormatter {
628    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
629    where
630        D: Deserializer<'de>,
631    {
632        struct FormatDeserializer;
633
634        impl<'d> Visitor<'d> for FormatDeserializer {
635            type Value = SelectedFormatter;
636
637            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
638                formatter.write_str("a valid formatter kind")
639            }
640            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
641            where
642                E: serde::de::Error,
643            {
644                if v == "auto" {
645                    Ok(Self::Value::Auto)
646                } else if v == "language_server" {
647                    Ok(Self::Value::List(FormatterList::Single(
648                        Formatter::LanguageServer { name: None },
649                    )))
650                } else {
651                    let ret: Result<FormatterList, _> =
652                        Deserialize::deserialize(v.into_deserializer());
653                    ret.map(SelectedFormatter::List)
654                }
655            }
656            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
657            where
658                A: MapAccess<'d>,
659            {
660                let ret: Result<FormatterList, _> =
661                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
662                ret.map(SelectedFormatter::List)
663            }
664            fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
665            where
666                A: SeqAccess<'d>,
667            {
668                let ret: Result<FormatterList, _> =
669                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
670                ret.map(SelectedFormatter::List)
671            }
672        }
673        deserializer.deserialize_any(FormatDeserializer)
674    }
675}
676
677/// Controls which formatters should be used when formatting code.
678#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
679#[serde(untagged)]
680pub enum FormatterList {
681    Single(Formatter),
682    Vec(Vec<Formatter>),
683}
684
685impl Default for FormatterList {
686    fn default() -> Self {
687        Self::Single(Formatter::default())
688    }
689}
690
691impl AsRef<[Formatter]> for FormatterList {
692    fn as_ref(&self) -> &[Formatter] {
693        match &self {
694            Self::Single(single) => std::slice::from_ref(single),
695            Self::Vec(v) => v,
696        }
697    }
698}
699
700/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
701#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
702#[serde(rename_all = "snake_case")]
703pub enum Formatter {
704    /// Format code using the current language server.
705    LanguageServer { name: Option<String> },
706    /// Format code using Zed's Prettier integration.
707    #[default]
708    Prettier,
709    /// Format code using an external command.
710    External {
711        /// The external program to run.
712        command: Arc<str>,
713        /// The arguments to pass to the program.
714        arguments: Option<Arc<[String]>>,
715    },
716    /// Files should be formatted using a code action executed by language servers.
717    CodeAction(String),
718}
719
720/// The settings for indent guides.
721#[skip_serializing_none]
722#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
723pub struct IndentGuideSettingsContent {
724    /// Whether to display indent guides in the editor.
725    ///
726    /// Default: true
727    pub enabled: Option<bool>,
728    /// The width of the indent guides in pixels, between 1 and 10.
729    ///
730    /// Default: 1
731    pub line_width: Option<u32>,
732    /// The width of the active indent guide in pixels, between 1 and 10.
733    ///
734    /// Default: 1
735    pub active_line_width: Option<u32>,
736    /// Determines how indent guides are colored.
737    ///
738    /// Default: Fixed
739    pub coloring: Option<IndentGuideColoring>,
740    /// Determines how indent guide backgrounds are colored.
741    ///
742    /// Default: Disabled
743    pub background_coloring: Option<IndentGuideBackgroundColoring>,
744}
745
746/// The task settings for a particular language.
747#[skip_serializing_none]
748#[derive(Debug, Clone, Deserialize, PartialEq, Serialize, JsonSchema, MergeFrom)]
749pub struct LanguageTaskSettingsContent {
750    /// Extra task variables to set for a particular language.
751    #[serde(default)]
752    pub variables: HashMap<String, String>,
753    pub enabled: Option<bool>,
754    /// Use LSP tasks over Zed language extension ones.
755    /// If no LSP tasks are returned due to error/timeout or regular execution,
756    /// Zed language extension tasks will be used instead.
757    ///
758    /// Other Zed tasks will still be shown:
759    /// * Zed task from either of the task config file
760    /// * Zed task from history (e.g. one-off task was spawned before)
761    pub prefer_lsp: Option<bool>,
762}
763
764/// Map from language name to settings.
765#[skip_serializing_none]
766#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
767pub struct LanguageToSettingsMap(pub HashMap<SharedString, LanguageSettingsContent>);
768
769/// Determines how indent guides are colored.
770#[derive(
771    Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom,
772)]
773#[serde(rename_all = "snake_case")]
774pub enum IndentGuideColoring {
775    /// Do not render any lines for indent guides.
776    Disabled,
777    /// Use the same color for all indentation levels.
778    #[default]
779    Fixed,
780    /// Use a different color for each indentation level.
781    IndentAware,
782}
783
784/// Determines how indent guide backgrounds are colored.
785#[derive(
786    Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom,
787)]
788#[serde(rename_all = "snake_case")]
789pub enum IndentGuideBackgroundColoring {
790    /// Do not render any background for indent guides.
791    #[default]
792    Disabled,
793    /// Use a different color for each indentation level.
794    IndentAware,
795}
796
797#[cfg(test)]
798mod test {
799    use super::*;
800
801    #[test]
802    fn test_formatter_deserialization() {
803        let raw_auto = "{\"formatter\": \"auto\"}";
804        let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
805        assert_eq!(settings.formatter, Some(SelectedFormatter::Auto));
806        let raw = "{\"formatter\": \"language_server\"}";
807        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
808        assert_eq!(
809            settings.formatter,
810            Some(SelectedFormatter::List(FormatterList::Single(
811                Formatter::LanguageServer { name: None }
812            )))
813        );
814        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
815        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
816        assert_eq!(
817            settings.formatter,
818            Some(SelectedFormatter::List(FormatterList::Vec(vec![
819                Formatter::LanguageServer { name: None }
820            ])))
821        );
822        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"prettier\"]}";
823        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
824        assert_eq!(
825            settings.formatter,
826            Some(SelectedFormatter::List(FormatterList::Vec(vec![
827                Formatter::LanguageServer { name: None },
828                Formatter::Prettier
829            ])))
830        );
831    }
832
833    #[test]
834    fn test_formatter_deserialization_invalid() {
835        let raw_auto = "{\"formatter\": {}}";
836        let result: Result<LanguageSettingsContent, _> = serde_json::from_str(raw_auto);
837        assert!(result.is_err());
838    }
839}