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