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