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