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