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