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