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