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