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