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