language.rs

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