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