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