language.rs

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