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, MergeFrom)]
573pub enum FormatOnSave {
574    /// Files should be formatted on save.
575    On,
576    /// Files should not be formatted on save.
577    Off,
578    List(FormatterList),
579}
580
581impl JsonSchema for FormatOnSave {
582    fn schema_name() -> Cow<'static, str> {
583        "OnSaveFormatter".into()
584    }
585
586    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
587        let formatter_schema = Formatter::json_schema(generator);
588
589        json_schema!({
590            "oneOf": [
591                {
592                    "type": "array",
593                    "items": formatter_schema
594                },
595                {
596                    "type": "string",
597                    "enum": ["on", "off", "language_server"]
598                },
599                formatter_schema
600            ]
601        })
602    }
603}
604
605impl Serialize for FormatOnSave {
606    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
607    where
608        S: serde::Serializer,
609    {
610        match self {
611            Self::On => serializer.serialize_str("on"),
612            Self::Off => serializer.serialize_str("off"),
613            Self::List(list) => list.serialize(serializer),
614        }
615    }
616}
617
618impl<'de> Deserialize<'de> for FormatOnSave {
619    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
620    where
621        D: Deserializer<'de>,
622    {
623        struct FormatDeserializer;
624
625        impl<'d> Visitor<'d> for FormatDeserializer {
626            type Value = FormatOnSave;
627
628            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
629                formatter.write_str("a valid on-save formatter kind")
630            }
631            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
632            where
633                E: serde::de::Error,
634            {
635                if v == "on" {
636                    Ok(Self::Value::On)
637                } else if v == "off" {
638                    Ok(Self::Value::Off)
639                } else if v == "language_server" {
640                    Ok(Self::Value::List(FormatterList::Single(
641                        Formatter::LanguageServer { name: None },
642                    )))
643                } else {
644                    let ret: Result<FormatterList, _> =
645                        Deserialize::deserialize(v.into_deserializer());
646                    ret.map(Self::Value::List)
647                }
648            }
649            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
650            where
651                A: MapAccess<'d>,
652            {
653                let ret: Result<FormatterList, _> =
654                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
655                ret.map(Self::Value::List)
656            }
657            fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
658            where
659                A: SeqAccess<'d>,
660            {
661                let ret: Result<FormatterList, _> =
662                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
663                ret.map(Self::Value::List)
664            }
665        }
666        deserializer.deserialize_any(FormatDeserializer)
667    }
668}
669
670/// Controls which formatter should be used when formatting code.
671#[derive(Clone, Debug, Default, PartialEq, Eq, MergeFrom)]
672pub enum SelectedFormatter {
673    /// Format files using Zed's Prettier integration (if applicable),
674    /// or falling back to formatting via language server.
675    #[default]
676    Auto,
677    List(FormatterList),
678}
679
680impl JsonSchema for SelectedFormatter {
681    fn schema_name() -> Cow<'static, str> {
682        "Formatter".into()
683    }
684
685    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
686        let formatter_schema = Formatter::json_schema(generator);
687
688        json_schema!({
689            "oneOf": [
690                {
691                    "type": "array",
692                    "items": formatter_schema
693                },
694                {
695                    "type": "string",
696                    "enum": ["auto", "language_server"]
697                },
698                formatter_schema
699            ]
700        })
701    }
702}
703
704impl Serialize for SelectedFormatter {
705    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
706    where
707        S: serde::Serializer,
708    {
709        match self {
710            SelectedFormatter::Auto => serializer.serialize_str("auto"),
711            SelectedFormatter::List(list) => list.serialize(serializer),
712        }
713    }
714}
715
716impl<'de> Deserialize<'de> for SelectedFormatter {
717    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
718    where
719        D: Deserializer<'de>,
720    {
721        struct FormatDeserializer;
722
723        impl<'d> Visitor<'d> for FormatDeserializer {
724            type Value = SelectedFormatter;
725
726            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
727                formatter.write_str("a valid formatter kind")
728            }
729            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
730            where
731                E: serde::de::Error,
732            {
733                if v == "auto" {
734                    Ok(Self::Value::Auto)
735                } else if v == "language_server" {
736                    Ok(Self::Value::List(FormatterList::Single(
737                        Formatter::LanguageServer { name: None },
738                    )))
739                } else {
740                    let ret: Result<FormatterList, _> =
741                        Deserialize::deserialize(v.into_deserializer());
742                    ret.map(SelectedFormatter::List)
743                }
744            }
745            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
746            where
747                A: MapAccess<'d>,
748            {
749                let ret: Result<FormatterList, _> =
750                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
751                ret.map(SelectedFormatter::List)
752            }
753            fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
754            where
755                A: SeqAccess<'d>,
756            {
757                let ret: Result<FormatterList, _> =
758                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
759                ret.map(SelectedFormatter::List)
760            }
761        }
762        deserializer.deserialize_any(FormatDeserializer)
763    }
764}
765
766/// Controls which formatters should be used when formatting code.
767#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
768#[serde(untagged)]
769pub enum FormatterList {
770    Single(Formatter),
771    Vec(Vec<Formatter>),
772}
773
774impl Default for FormatterList {
775    fn default() -> Self {
776        Self::Single(Formatter::default())
777    }
778}
779
780impl AsRef<[Formatter]> for FormatterList {
781    fn as_ref(&self) -> &[Formatter] {
782        match &self {
783            Self::Single(single) => std::slice::from_ref(single),
784            Self::Vec(v) => v,
785        }
786    }
787}
788
789/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
790#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
791#[serde(rename_all = "snake_case")]
792pub enum Formatter {
793    /// Format code using the current language server.
794    LanguageServer { name: Option<String> },
795    /// Format code using Zed's Prettier integration.
796    #[default]
797    Prettier,
798    /// Format code using an external command.
799    External {
800        /// The external program to run.
801        command: Arc<str>,
802        /// The arguments to pass to the program.
803        arguments: Option<Arc<[String]>>,
804    },
805    /// Files should be formatted using a code action executed by language servers.
806    CodeAction(String),
807}
808
809/// The settings for indent guides.
810#[skip_serializing_none]
811#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
812pub struct IndentGuideSettingsContent {
813    /// Whether to display indent guides in the editor.
814    ///
815    /// Default: true
816    pub enabled: Option<bool>,
817    /// The width of the indent guides in pixels, between 1 and 10.
818    ///
819    /// Default: 1
820    pub line_width: Option<u32>,
821    /// The width of the active indent guide in pixels, between 1 and 10.
822    ///
823    /// Default: 1
824    pub active_line_width: Option<u32>,
825    /// Determines how indent guides are colored.
826    ///
827    /// Default: Fixed
828    pub coloring: Option<IndentGuideColoring>,
829    /// Determines how indent guide backgrounds are colored.
830    ///
831    /// Default: Disabled
832    pub background_coloring: Option<IndentGuideBackgroundColoring>,
833}
834
835/// The task settings for a particular language.
836#[skip_serializing_none]
837#[derive(Debug, Clone, Deserialize, PartialEq, Serialize, JsonSchema, MergeFrom)]
838pub struct LanguageTaskSettingsContent {
839    /// Extra task variables to set for a particular language.
840    #[serde(default)]
841    pub variables: HashMap<String, String>,
842    pub enabled: Option<bool>,
843    /// Use LSP tasks over Zed language extension ones.
844    /// If no LSP tasks are returned due to error/timeout or regular execution,
845    /// Zed language extension tasks will be used instead.
846    ///
847    /// Other Zed tasks will still be shown:
848    /// * Zed task from either of the task config file
849    /// * Zed task from history (e.g. one-off task was spawned before)
850    pub prefer_lsp: Option<bool>,
851}
852
853/// Map from language name to settings.
854#[skip_serializing_none]
855#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
856pub struct LanguageToSettingsMap(pub HashMap<SharedString, LanguageSettingsContent>);
857
858/// Determines how indent guides are colored.
859#[derive(
860    Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom,
861)]
862#[serde(rename_all = "snake_case")]
863pub enum IndentGuideColoring {
864    /// Do not render any lines for indent guides.
865    Disabled,
866    /// Use the same color for all indentation levels.
867    #[default]
868    Fixed,
869    /// Use a different color for each indentation level.
870    IndentAware,
871}
872
873/// Determines how indent guide backgrounds are colored.
874#[derive(
875    Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom,
876)]
877#[serde(rename_all = "snake_case")]
878pub enum IndentGuideBackgroundColoring {
879    /// Do not render any background for indent guides.
880    #[default]
881    Disabled,
882    /// Use a different color for each indentation level.
883    IndentAware,
884}
885
886#[cfg(test)]
887mod test {
888    use super::*;
889
890    #[test]
891    fn test_formatter_deserialization() {
892        let raw_auto = "{\"formatter\": \"auto\"}";
893        let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
894        assert_eq!(settings.formatter, Some(SelectedFormatter::Auto));
895        let raw = "{\"formatter\": \"language_server\"}";
896        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
897        assert_eq!(
898            settings.formatter,
899            Some(SelectedFormatter::List(FormatterList::Single(
900                Formatter::LanguageServer { name: None }
901            )))
902        );
903        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
904        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
905        assert_eq!(
906            settings.formatter,
907            Some(SelectedFormatter::List(FormatterList::Vec(vec![
908                Formatter::LanguageServer { name: None }
909            ])))
910        );
911        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"prettier\"]}";
912        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
913        assert_eq!(
914            settings.formatter,
915            Some(SelectedFormatter::List(FormatterList::Vec(vec![
916                Formatter::LanguageServer { name: None },
917                Formatter::Prettier
918            ])))
919        );
920    }
921
922    #[test]
923    fn test_formatter_deserialization_invalid() {
924        let raw_auto = "{\"formatter\": {}}";
925        let result: Result<LanguageSettingsContent, _> = serde_json::from_str(raw_auto);
926        assert!(result.is_err());
927    }
928}