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