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