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