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