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