language.rs

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