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