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