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