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