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