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