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