language.rs

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