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<IndentGuideSettings>,
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<JsxTagAutoCloseSettings>,
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<LanguageTaskConfig>,
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<CompletionSettings>,
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    #[serde(default)]
316    pub space: Option<String>,
317    #[serde(default)]
318    pub tab: Option<String>,
319}
320
321impl WhitespaceMap {
322    pub fn space(&self) -> SharedString {
323        self.space
324            .as_ref()
325            .map_or_else(|| SharedString::from(""), |s| SharedString::from(s))
326    }
327
328    pub fn tab(&self) -> SharedString {
329        self.tab
330            .as_ref()
331            .map_or_else(|| SharedString::from(""), |s| SharedString::from(s))
332    }
333}
334
335/// The behavior of `editor::Rewrap`.
336#[derive(Debug, PartialEq, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]
337#[serde(rename_all = "snake_case")]
338pub enum RewrapBehavior {
339    /// Only rewrap within comments.
340    #[default]
341    InComments,
342    /// Only rewrap within the current selection(s).
343    InSelections,
344    /// Allow rewrapping anywhere.
345    Anywhere,
346}
347
348#[skip_serializing_none]
349#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
350pub struct JsxTagAutoCloseSettings {
351    /// Enables or disables auto-closing of JSX tags.
352    // todo! option
353    #[serde(default)]
354    pub enabled: bool,
355}
356
357/// The settings for inlay hints.
358/// todo!() the fields of this struct should likely be optional,
359/// and a similar struct exposed from the language crate.
360#[skip_serializing_none]
361#[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
362pub struct InlayHintSettingsContent {
363    /// Global switch to toggle hints on and off.
364    ///
365    /// Default: false
366    pub enabled: Option<bool>,
367    /// Global switch to toggle inline values on and off when debugging.
368    ///
369    /// Default: true
370    pub show_value_hints: Option<bool>,
371    /// Whether type hints should be shown.
372    ///
373    /// Default: true
374    pub show_type_hints: Option<bool>,
375    /// Whether parameter hints should be shown.
376    ///
377    /// Default: true
378    pub show_parameter_hints: Option<bool>,
379    /// Whether other hints should be shown.
380    ///
381    /// Default: true
382    pub show_other_hints: Option<bool>,
383    /// Whether to show a background for inlay hints.
384    ///
385    /// If set to `true`, the background will use the `hint.background` color
386    /// from the current theme.
387    ///
388    /// Default: false
389    pub show_background: Option<bool>,
390    /// Whether or not to debounce inlay hints updates after buffer edits.
391    ///
392    /// Set to 0 to disable debouncing.
393    ///
394    /// Default: 700
395    pub edit_debounce_ms: Option<u64>,
396    /// Whether or not to debounce inlay hints updates after buffer scrolls.
397    ///
398    /// Set to 0 to disable debouncing.
399    ///
400    /// Default: 50
401    pub scroll_debounce_ms: Option<u64>,
402    /// Toggles inlay hints (hides or shows) when the user presses the modifiers specified.
403    /// If only a subset of the modifiers specified is pressed, hints are not toggled.
404    /// If no modifiers are specified, this is equivalent to `null`.
405    ///
406    /// Default: null
407    pub toggle_on_modifiers_press: Option<Modifiers>,
408}
409
410/// The kind of an inlay hint.
411#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
412pub enum InlayHintKind {
413    /// An inlay hint for a type.
414    Type,
415    /// An inlay hint for a parameter.
416    Parameter,
417}
418
419impl InlayHintKind {
420    /// Returns the [`InlayHintKind`]fromthe given name.
421    ///
422    /// Returns `None` if `name` does not match any of the expected
423    /// string representations.
424    pub fn from_name(name: &str) -> Option<Self> {
425        match name {
426            "type" => Some(InlayHintKind::Type),
427            "parameter" => Some(InlayHintKind::Parameter),
428            _ => None,
429        }
430    }
431
432    /// Returns the name of this [`InlayHintKind`].
433    pub fn name(&self) -> &'static str {
434        match self {
435            InlayHintKind::Type => "type",
436            InlayHintKind::Parameter => "parameter",
437        }
438    }
439}
440
441/// Controls how completions are processedfor this anguage.
442#[skip_serializing_none]
443#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
444#[serde(rename_all = "snake_case")]
445pub struct CompletionSettings {
446    /// Controls how words are completed.
447    /// For large documents, not all words may be fetched for completion.
448    ///
449    /// Default: `fallback`
450    #[serde(default = "default_words_completion_mode")]
451    pub words: WordsCompletionMode,
452    /// How many characters has to be in the completions query to automatically show the words-based completions.
453    /// Before that value, it's still possible to trigger the words-based completion manually with the corresponding editor command.
454    ///
455    /// Default: 3
456    #[serde(default = "default_3")]
457    pub words_min_length: usize,
458    /// Whether to fetch LSP completions or not.
459    ///
460    /// Default: true
461    #[serde(default = "default_true")]
462    pub lsp: bool,
463    /// When fetching LSP completions, determines how long to wait for a response of a particular server.
464    /// When set to 0, waits indefinitely.
465    ///
466    /// Default: 0
467    #[serde(default)]
468    pub lsp_fetch_timeout_ms: u64,
469    /// Controls how LSP completions are inserted.
470    ///
471    /// Default: "replace_suffix"
472    #[serde(default = "default_lsp_insert_mode")]
473    pub lsp_insert_mode: 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
505fn default_words_completion_mode() -> WordsCompletionMode {
506    WordsCompletionMode::Fallback
507}
508
509fn default_lsp_insert_mode() -> LspInsertMode {
510    LspInsertMode::ReplaceSuffix
511}
512
513fn default_3() -> usize {
514    3
515}
516
517/// Allows to enable/disable formatting with Prettier
518/// and configure default Prettier, used when no project-level Prettier installation is found.
519/// Prettier formatting is disabled by default.
520#[skip_serializing_none]
521#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
522pub struct PrettierSettingsContent {
523    /// Enables or disables formatting with Prettier for a given language.
524    #[serde(default)]
525    pub allowed: bool,
526
527    /// Forces Prettier integration to use a specific parser name when formatting files with the language.
528    #[serde(default)]
529    pub parser: Option<String>,
530
531    /// Forces Prettier integration to use specific plugins when formatting files with the language.
532    /// The default Prettier will be installed with these plugins.
533    #[serde(default)]
534    pub plugins: HashSet<String>,
535
536    /// Default Prettier options, in the format as in package.json section for Prettier.
537    /// If project installs Prettier via its package.json, these options will be ignored.
538    #[serde(flatten)]
539    pub options: HashMap<String, serde_json::Value>,
540}
541
542/// Controls the behavior of formatting files when they are saved.
543#[derive(Debug, Clone, PartialEq, Eq)]
544pub enum FormatOnSave {
545    /// Files should be formatted on save.
546    On,
547    /// Files should not be formatted on save.
548    Off,
549    List(FormatterList),
550}
551
552impl JsonSchema for FormatOnSave {
553    fn schema_name() -> Cow<'static, str> {
554        "OnSaveFormatter".into()
555    }
556
557    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
558        let formatter_schema = Formatter::json_schema(generator);
559
560        json_schema!({
561            "oneOf": [
562                {
563                    "type": "array",
564                    "items": formatter_schema
565                },
566                {
567                    "type": "string",
568                    "enum": ["on", "off", "language_server"]
569                },
570                formatter_schema
571            ]
572        })
573    }
574}
575
576impl Serialize for FormatOnSave {
577    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
578    where
579        S: serde::Serializer,
580    {
581        match self {
582            Self::On => serializer.serialize_str("on"),
583            Self::Off => serializer.serialize_str("off"),
584            Self::List(list) => list.serialize(serializer),
585        }
586    }
587}
588
589impl<'de> Deserialize<'de> for FormatOnSave {
590    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
591    where
592        D: Deserializer<'de>,
593    {
594        struct FormatDeserializer;
595
596        impl<'d> Visitor<'d> for FormatDeserializer {
597            type Value = FormatOnSave;
598
599            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
600                formatter.write_str("a valid on-save formatter kind")
601            }
602            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
603            where
604                E: serde::de::Error,
605            {
606                if v == "on" {
607                    Ok(Self::Value::On)
608                } else if v == "off" {
609                    Ok(Self::Value::Off)
610                } else if v == "language_server" {
611                    Ok(Self::Value::List(FormatterList::Single(
612                        Formatter::LanguageServer { name: None },
613                    )))
614                } else {
615                    let ret: Result<FormatterList, _> =
616                        Deserialize::deserialize(v.into_deserializer());
617                    ret.map(Self::Value::List)
618                }
619            }
620            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
621            where
622                A: MapAccess<'d>,
623            {
624                let ret: Result<FormatterList, _> =
625                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
626                ret.map(Self::Value::List)
627            }
628            fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
629            where
630                A: SeqAccess<'d>,
631            {
632                let ret: Result<FormatterList, _> =
633                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
634                ret.map(Self::Value::List)
635            }
636        }
637        deserializer.deserialize_any(FormatDeserializer)
638    }
639}
640
641/// Controls which formatter should be used when formatting code.
642#[derive(Clone, Debug, Default, PartialEq, Eq)]
643pub enum SelectedFormatter {
644    /// Format files using Zed's Prettier integration (if applicable),
645    /// or falling back to formatting via language server.
646    #[default]
647    Auto,
648    List(FormatterList),
649}
650
651impl JsonSchema for SelectedFormatter {
652    fn schema_name() -> Cow<'static, str> {
653        "Formatter".into()
654    }
655
656    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
657        let formatter_schema = Formatter::json_schema(generator);
658
659        json_schema!({
660            "oneOf": [
661                {
662                    "type": "array",
663                    "items": formatter_schema
664                },
665                {
666                    "type": "string",
667                    "enum": ["auto", "language_server"]
668                },
669                formatter_schema
670            ]
671        })
672    }
673}
674
675impl Serialize for SelectedFormatter {
676    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
677    where
678        S: serde::Serializer,
679    {
680        match self {
681            SelectedFormatter::Auto => serializer.serialize_str("auto"),
682            SelectedFormatter::List(list) => list.serialize(serializer),
683        }
684    }
685}
686
687impl<'de> Deserialize<'de> for SelectedFormatter {
688    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
689    where
690        D: Deserializer<'de>,
691    {
692        struct FormatDeserializer;
693
694        impl<'d> Visitor<'d> for FormatDeserializer {
695            type Value = SelectedFormatter;
696
697            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
698                formatter.write_str("a valid formatter kind")
699            }
700            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
701            where
702                E: serde::de::Error,
703            {
704                if v == "auto" {
705                    Ok(Self::Value::Auto)
706                } else if v == "language_server" {
707                    Ok(Self::Value::List(FormatterList::Single(
708                        Formatter::LanguageServer { name: None },
709                    )))
710                } else {
711                    let ret: Result<FormatterList, _> =
712                        Deserialize::deserialize(v.into_deserializer());
713                    ret.map(SelectedFormatter::List)
714                }
715            }
716            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
717            where
718                A: MapAccess<'d>,
719            {
720                let ret: Result<FormatterList, _> =
721                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
722                ret.map(SelectedFormatter::List)
723            }
724            fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
725            where
726                A: SeqAccess<'d>,
727            {
728                let ret: Result<FormatterList, _> =
729                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
730                ret.map(SelectedFormatter::List)
731            }
732        }
733        deserializer.deserialize_any(FormatDeserializer)
734    }
735}
736
737/// Controls which formatters should be used when formatting code.
738#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
739#[serde(untagged)]
740pub enum FormatterList {
741    Single(Formatter),
742    Vec(Vec<Formatter>),
743}
744
745impl Default for FormatterList {
746    fn default() -> Self {
747        Self::Single(Formatter::default())
748    }
749}
750
751impl AsRef<[Formatter]> for FormatterList {
752    fn as_ref(&self) -> &[Formatter] {
753        match &self {
754            Self::Single(single) => std::slice::from_ref(single),
755            Self::Vec(v) => v,
756        }
757    }
758}
759
760/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
761#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
762#[serde(rename_all = "snake_case")]
763pub enum Formatter {
764    /// Format code using the current language server.
765    LanguageServer { name: Option<String> },
766    /// Format code using Zed's Prettier integration.
767    #[default]
768    Prettier,
769    /// Format code using an external command.
770    External {
771        /// The external program to run.
772        command: Arc<str>,
773        /// The arguments to pass to the program.
774        arguments: Option<Arc<[String]>>,
775    },
776    /// Files should be formatted using code actions executed by language servers.
777    CodeActions(HashMap<String, bool>),
778}
779
780/// The settings for indent guides.
781#[skip_serializing_none]
782#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
783pub struct IndentGuideSettings {
784    /// Whether to display indent guides in the editor.
785    ///
786    /// Default: true
787    #[serde(default = "default_true")]
788    pub enabled: bool,
789    /// The width of the indent guides in pixels, between 1 and 10.
790    ///
791    /// Default: 1
792    #[serde(default = "line_width")]
793    pub line_width: u32,
794    /// The width of the active indent guide in pixels, between 1 and 10.
795    ///
796    /// Default: 1
797    #[serde(default = "active_line_width")]
798    pub active_line_width: u32,
799    /// Determines how indent guides are colored.
800    ///
801    /// Default: Fixed
802    #[serde(default)]
803    pub coloring: IndentGuideColoring,
804    /// Determines how indent guide backgrounds are colored.
805    ///
806    /// Default: Disabled
807    #[serde(default)]
808    pub background_coloring: IndentGuideBackgroundColoring,
809}
810
811fn default_true() -> bool {
812    true
813}
814
815fn line_width() -> u32 {
816    1
817}
818
819fn active_line_width() -> u32 {
820    line_width()
821}
822
823/// The task settings for a particular language.
824#[skip_serializing_none]
825#[derive(Debug, Clone, Deserialize, PartialEq, Serialize, JsonSchema)]
826pub struct LanguageTaskConfig {
827    /// Extra task variables to set for a particular language.
828    #[serde(default)]
829    pub variables: HashMap<String, String>,
830    #[serde(default = "default_true")]
831    pub enabled: bool,
832    /// Use LSP tasks over Zed language extension ones.
833    /// If no LSP tasks are returned due to error/timeout or regular execution,
834    /// Zed language extension tasks will be used instead.
835    ///
836    /// Other Zed tasks will still be shown:
837    /// * Zed task from either of the task config file
838    /// * Zed task from history (e.g. one-off task was spawned before)
839    #[serde(default = "default_true")]
840    pub prefer_lsp: bool,
841}
842
843/// Map from language name to settings. Its `ParameterizedJsonSchema` allows only known language
844/// names in the keys.
845#[skip_serializing_none]
846#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
847pub struct LanguageToSettingsMap(pub HashMap<SharedString, LanguageSettingsContent>);
848
849inventory::submit! {
850    ParameterizedJsonSchema {
851        add_and_get_ref: |generator, params, _cx| {
852            let language_settings_content_ref = generator
853                .subschema_for::<LanguageSettingsContent>()
854                .to_value();
855            replace_subschema::<LanguageToSettingsMap>(generator, || json_schema!({
856                "type": "object",
857                "properties": params
858                    .language_names
859                    .iter()
860                    .map(|name| {
861                        (
862                            name.clone(),
863                            language_settings_content_ref.clone(),
864                        )
865                    })
866                    .collect::<serde_json::Map<_, _>>()
867            }))
868        }
869    }
870}
871
872/// Determines how indent guides are colored.
873#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
874#[serde(rename_all = "snake_case")]
875pub enum IndentGuideColoring {
876    /// Do not render any lines for indent guides.
877    Disabled,
878    /// Use the same color for all indentation levels.
879    #[default]
880    Fixed,
881    /// Use a different color for each indentation level.
882    IndentAware,
883}
884
885/// Determines how indent guide backgrounds are colored.
886#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
887#[serde(rename_all = "snake_case")]
888pub enum IndentGuideBackgroundColoring {
889    /// Do not render any background for indent guides.
890    #[default]
891    Disabled,
892    /// Use a different color for each indentation level.
893    IndentAware,
894}
895
896#[cfg(test)]
897mod test {
898    use super::*;
899
900    #[test]
901    fn test_formatter_deserialization() {
902        let raw_auto = "{\"formatter\": \"auto\"}";
903        let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
904        assert_eq!(settings.formatter, Some(SelectedFormatter::Auto));
905        let raw = "{\"formatter\": \"language_server\"}";
906        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
907        assert_eq!(
908            settings.formatter,
909            Some(SelectedFormatter::List(FormatterList::Single(
910                Formatter::LanguageServer { name: None }
911            )))
912        );
913        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
914        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
915        assert_eq!(
916            settings.formatter,
917            Some(SelectedFormatter::List(FormatterList::Vec(vec![
918                Formatter::LanguageServer { name: None }
919            ])))
920        );
921        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"prettier\"]}";
922        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
923        assert_eq!(
924            settings.formatter,
925            Some(SelectedFormatter::List(FormatterList::Vec(vec![
926                Formatter::LanguageServer { name: None },
927                Formatter::Prettier
928            ])))
929        );
930    }
931
932    #[test]
933    fn test_formatter_deserialization_invalid() {
934        let raw_auto = "{\"formatter\": {}}";
935        let result: Result<LanguageSettingsContent, _> = serde_json::from_str(raw_auto);
936        assert!(result.is_err());
937    }
938}