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 Supermaven,
85 Zed,
86 Codestral,
87 Ollama,
88 OpenAiCompatibleApi,
89 Sweep,
90 Mercury,
91 Experimental(&'static str),
92}
93
94pub const EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME: &str = "zeta2";
95
96impl<'de> Deserialize<'de> for EditPredictionProvider {
97 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
98 where
99 D: serde::Deserializer<'de>,
100 {
101 #[derive(Deserialize)]
102 #[serde(rename_all = "snake_case")]
103 pub enum Content {
104 None,
105 Copilot,
106 Supermaven,
107 Zed,
108 Codestral,
109 Ollama,
110 OpenAiCompatibleApi,
111 Sweep,
112 Mercury,
113 Experimental(String),
114 }
115
116 Ok(match Content::deserialize(deserializer)? {
117 Content::None => EditPredictionProvider::None,
118 Content::Copilot => EditPredictionProvider::Copilot,
119 Content::Supermaven => EditPredictionProvider::Supermaven,
120 Content::Zed => EditPredictionProvider::Zed,
121 Content::Codestral => EditPredictionProvider::Codestral,
122 Content::Ollama => EditPredictionProvider::Ollama,
123 Content::OpenAiCompatibleApi => EditPredictionProvider::OpenAiCompatibleApi,
124 Content::Sweep => EditPredictionProvider::Sweep,
125 Content::Mercury => EditPredictionProvider::Mercury,
126 Content::Experimental(name)
127 if name == EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME =>
128 {
129 EditPredictionProvider::Experimental(
130 EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
131 )
132 }
133 Content::Experimental(name) => {
134 return Err(D::Error::custom(format!(
135 "Unknown experimental edit prediction provider: {}",
136 name
137 )));
138 }
139 })
140 }
141}
142
143impl EditPredictionProvider {
144 pub fn is_zed(&self) -> bool {
145 match self {
146 EditPredictionProvider::Zed => true,
147 EditPredictionProvider::None
148 | EditPredictionProvider::Copilot
149 | EditPredictionProvider::Supermaven
150 | EditPredictionProvider::Codestral
151 | EditPredictionProvider::Ollama
152 | EditPredictionProvider::OpenAiCompatibleApi
153 | EditPredictionProvider::Sweep
154 | EditPredictionProvider::Mercury
155 | EditPredictionProvider::Experimental(_) => false,
156 }
157 }
158
159 pub fn display_name(&self) -> Option<&'static str> {
160 match self {
161 EditPredictionProvider::Zed => Some("Zed AI"),
162 EditPredictionProvider::Copilot => Some("GitHub Copilot"),
163 EditPredictionProvider::Supermaven => Some("Supermaven"),
164 EditPredictionProvider::Codestral => Some("Codestral"),
165 EditPredictionProvider::Sweep => Some("Sweep"),
166 EditPredictionProvider::Mercury => Some("Mercury"),
167 EditPredictionProvider::Experimental(
168 EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
169 ) => Some("Zeta2"),
170 EditPredictionProvider::None | EditPredictionProvider::Experimental(_) => None,
171 EditPredictionProvider::Ollama => Some("Ollama"),
172 EditPredictionProvider::OpenAiCompatibleApi => Some("OpenAI-Compatible API"),
173 }
174 }
175}
176
177/// The contents of the edit prediction settings.
178#[with_fallible_options]
179#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
180pub struct EditPredictionSettingsContent {
181 /// Determines which edit prediction provider to use.
182 pub provider: Option<EditPredictionProvider>,
183 /// A list of globs representing files that edit predictions should be disabled for.
184 /// This list adds to a pre-existing, sensible default set of globs.
185 /// Any additional ones you add are combined with them.
186 pub disabled_globs: Option<Vec<String>>,
187 /// The mode used to display edit predictions in the buffer.
188 /// Provider support required.
189 pub mode: Option<EditPredictionsMode>,
190 /// Settings specific to GitHub Copilot.
191 pub copilot: Option<CopilotSettingsContent>,
192 /// Settings specific to Codestral.
193 pub codestral: Option<CodestralSettingsContent>,
194 /// Settings specific to Sweep.
195 pub sweep: Option<SweepSettingsContent>,
196 /// Settings specific to Ollama.
197 pub ollama: Option<OllamaEditPredictionSettingsContent>,
198 /// Settings specific to using custom OpenAI-compatible servers for edit prediction.
199 pub open_ai_compatible_api: Option<CustomEditPredictionProviderSettingsContent>,
200 /// Whether edit predictions are enabled in the assistant prompt editor.
201 /// This has no effect if globally disabled.
202 pub enabled_in_text_threads: Option<bool>,
203 /// The directory where manually captured edit prediction examples are stored.
204 pub examples_dir: Option<Arc<Path>>,
205}
206
207#[with_fallible_options]
208#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
209pub struct CustomEditPredictionProviderSettingsContent {
210 /// Api URL to use for completions.
211 ///
212 /// Default: ""
213 pub api_url: Option<String>,
214 /// The prompt format to use for completions. Set to `""` to have the format be derived from the model name.
215 ///
216 /// Default: ""
217 pub prompt_format: Option<EditPredictionPromptFormat>,
218 /// The name of the model.
219 ///
220 /// Default: ""
221 pub model: Option<String>,
222 /// Maximum tokens to generate for FIM models.
223 /// This setting does not apply to sweep models.
224 ///
225 /// Default: 256
226 pub max_output_tokens: Option<u32>,
227}
228
229#[derive(
230 Copy,
231 Clone,
232 Debug,
233 Default,
234 PartialEq,
235 Eq,
236 Serialize,
237 Deserialize,
238 JsonSchema,
239 MergeFrom,
240 strum::VariantArray,
241 strum::VariantNames,
242)]
243#[serde(rename_all = "snake_case")]
244pub enum EditPredictionPromptFormat {
245 #[default]
246 Infer,
247 Zeta,
248 CodeLlama,
249 StarCoder,
250 DeepseekCoder,
251 Qwen,
252 CodeGemma,
253 Codestral,
254 Glm,
255}
256
257#[with_fallible_options]
258#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
259pub struct CopilotSettingsContent {
260 /// HTTP/HTTPS proxy to use for Copilot.
261 ///
262 /// Default: none
263 pub proxy: Option<String>,
264 /// Disable certificate verification for the proxy (not recommended).
265 ///
266 /// Default: false
267 pub proxy_no_verify: Option<bool>,
268 /// Enterprise URI for Copilot.
269 ///
270 /// Default: none
271 pub enterprise_uri: Option<String>,
272 /// Whether the Copilot Next Edit Suggestions feature is enabled.
273 ///
274 /// Default: true
275 pub enable_next_edit_suggestions: Option<bool>,
276}
277
278#[with_fallible_options]
279#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
280pub struct CodestralSettingsContent {
281 /// Model to use for completions.
282 ///
283 /// Default: "codestral-latest"
284 pub model: Option<String>,
285 /// Maximum tokens to generate.
286 ///
287 /// Default: 150
288 pub max_tokens: Option<u32>,
289 /// Api URL to use for completions.
290 ///
291 /// Default: "https://codestral.mistral.ai"
292 pub api_url: Option<String>,
293}
294
295#[with_fallible_options]
296#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
297pub struct SweepSettingsContent {
298 /// When enabled, Sweep will not store edit prediction inputs or outputs.
299 /// When disabled, Sweep may collect data including buffer contents,
300 /// diagnostics, file paths, repository names, and generated predictions
301 /// to improve the service.
302 ///
303 /// Default: false
304 pub privacy_mode: Option<bool>,
305}
306
307/// Ollama model name for edit predictions.
308#[with_fallible_options]
309#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq, Eq)]
310#[serde(transparent)]
311pub struct OllamaModelName(pub String);
312
313impl AsRef<str> for OllamaModelName {
314 fn as_ref(&self) -> &str {
315 &self.0
316 }
317}
318
319impl From<String> for OllamaModelName {
320 fn from(value: String) -> Self {
321 Self(value)
322 }
323}
324
325impl From<OllamaModelName> for String {
326 fn from(value: OllamaModelName) -> Self {
327 value.0
328 }
329}
330
331#[with_fallible_options]
332#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
333pub struct OllamaEditPredictionSettingsContent {
334 /// Model to use for completions.
335 ///
336 /// Default: none
337 pub model: Option<OllamaModelName>,
338 /// Maximum tokens to generate for FIM models.
339 /// This setting does not apply to sweep models.
340 ///
341 /// Default: 256
342 pub max_output_tokens: Option<u32>,
343 /// Api URL to use for completions.
344 ///
345 /// Default: "http://localhost:11434"
346 pub api_url: Option<String>,
347
348 /// The prompt format to use for completions. Set to `""` to have the format be derived from the model name.
349 ///
350 /// Default: ""
351 pub prompt_format: Option<EditPredictionPromptFormat>,
352}
353
354/// The mode in which edit predictions should be displayed.
355#[derive(
356 Copy,
357 Clone,
358 Debug,
359 Default,
360 Eq,
361 PartialEq,
362 Serialize,
363 Deserialize,
364 JsonSchema,
365 MergeFrom,
366 strum::VariantArray,
367 strum::VariantNames,
368)]
369#[serde(rename_all = "snake_case")]
370pub enum EditPredictionsMode {
371 /// If provider supports it, display inline when holding modifier key (e.g., alt).
372 /// Otherwise, eager preview is used.
373 #[serde(alias = "auto")]
374 Subtle,
375 /// Display inline when there are no language server completions available.
376 #[default]
377 #[serde(alias = "eager_preview")]
378 Eager,
379}
380
381/// Controls the soft-wrapping behavior in the editor.
382#[derive(
383 Copy,
384 Clone,
385 Debug,
386 Serialize,
387 Deserialize,
388 PartialEq,
389 Eq,
390 JsonSchema,
391 MergeFrom,
392 strum::VariantArray,
393 strum::VariantNames,
394)]
395#[serde(rename_all = "snake_case")]
396pub enum SoftWrap {
397 /// Prefer a single line generally, unless an overly long line is encountered.
398 None,
399 /// Deprecated: use None instead. Left to avoid breaking existing users' configs.
400 /// Prefer a single line generally, unless an overly long line is encountered.
401 PreferLine,
402 /// Soft wrap lines that exceed the editor width.
403 EditorWidth,
404 /// Soft wrap lines at the preferred line length.
405 PreferredLineLength,
406 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
407 Bounded,
408}
409
410/// The settings for a particular language.
411#[with_fallible_options]
412#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
413pub struct LanguageSettingsContent {
414 /// How many columns a tab should occupy.
415 ///
416 /// Default: 4
417 #[schemars(range(min = 1, max = 128))]
418 pub tab_size: Option<NonZeroU32>,
419 /// Whether to indent lines using tab characters, as opposed to multiple
420 /// spaces.
421 ///
422 /// Default: false
423 pub hard_tabs: Option<bool>,
424 /// How to soft-wrap long lines of text.
425 ///
426 /// Default: none
427 pub soft_wrap: Option<SoftWrap>,
428 /// The column at which to soft-wrap lines, for buffers where soft-wrap
429 /// is enabled.
430 ///
431 /// Default: 80
432 pub preferred_line_length: Option<u32>,
433 /// Whether to show wrap guides in the editor. Setting this to true will
434 /// show a guide at the 'preferred_line_length' value if softwrap is set to
435 /// 'preferred_line_length', and will show any additional guides as specified
436 /// by the 'wrap_guides' setting.
437 ///
438 /// Default: true
439 pub show_wrap_guides: Option<bool>,
440 /// Character counts at which to show wrap guides in the editor.
441 ///
442 /// Default: []
443 pub wrap_guides: Option<Vec<usize>>,
444 /// Indent guide related settings.
445 pub indent_guides: Option<IndentGuideSettingsContent>,
446 /// Whether or not to perform a buffer format before saving.
447 ///
448 /// Default: on
449 pub format_on_save: Option<FormatOnSave>,
450 /// Whether or not to remove any trailing whitespace from lines of a buffer
451 /// before saving it.
452 ///
453 /// Default: true
454 pub remove_trailing_whitespace_on_save: Option<bool>,
455 /// Whether or not to ensure there's a single newline at the end of a buffer
456 /// when saving it.
457 ///
458 /// Default: true
459 pub ensure_final_newline_on_save: Option<bool>,
460 /// How to perform a buffer format.
461 ///
462 /// Default: auto
463 pub formatter: Option<FormatterList>,
464 /// Zed's Prettier integration settings.
465 /// Allows to enable/disable formatting with Prettier
466 /// and configure default Prettier, used when no project-level Prettier installation is found.
467 ///
468 /// Default: off
469 pub prettier: Option<PrettierSettingsContent>,
470 /// Whether to automatically close JSX tags.
471 pub jsx_tag_auto_close: Option<JsxTagAutoCloseSettingsContent>,
472 /// Whether to use language servers to provide code intelligence.
473 ///
474 /// Default: true
475 pub enable_language_server: Option<bool>,
476 /// The list of language servers to use (or disable) for this language.
477 ///
478 /// This array should consist of language server IDs, as well as the following
479 /// special tokens:
480 /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
481 /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
482 ///
483 /// Default: ["..."]
484 pub language_servers: Option<Vec<String>>,
485 /// Controls how semantic tokens from language servers are used for syntax highlighting.
486 ///
487 /// Options:
488 /// - "off": Do not request semantic tokens from language servers.
489 /// - "combined": Use LSP semantic tokens together with tree-sitter highlighting.
490 /// - "full": Use LSP semantic tokens exclusively, replacing tree-sitter highlighting.
491 ///
492 /// Default: "off"
493 pub semantic_tokens: Option<SemanticTokens>,
494 /// Controls whether folding ranges from language servers are used instead of
495 /// tree-sitter and indent-based folding.
496 ///
497 /// Options:
498 /// - "off": Use tree-sitter and indent-based folding (default).
499 /// - "on": Use LSP folding wherever possible, falling back to tree-sitter and indent-based folding when no results were returned by the server.
500 ///
501 /// Default: "off"
502 pub document_folding_ranges: Option<DocumentFoldingRanges>,
503 /// Controls the source of document symbols used for outlines and breadcrumbs.
504 ///
505 /// Options:
506 /// - "off": Use tree-sitter queries to compute document symbols (default).
507 /// - "on": Use the language server's `textDocument/documentSymbol` LSP response. When enabled, tree-sitter is not used for document symbols.
508 ///
509 /// Default: "off"
510 pub document_symbols: Option<DocumentSymbols>,
511 /// Controls where the `editor::Rewrap` action is allowed for this language.
512 ///
513 /// Note: This setting has no effect in Vim mode, as rewrap is already
514 /// allowed everywhere.
515 ///
516 /// Default: "in_comments"
517 pub allow_rewrap: Option<RewrapBehavior>,
518 /// Controls whether edit predictions are shown immediately (true)
519 /// or manually by triggering `editor::ShowEditPrediction` (false).
520 ///
521 /// Default: true
522 pub show_edit_predictions: Option<bool>,
523 /// Controls whether edit predictions are shown in the given language
524 /// scopes.
525 ///
526 /// Example: ["string", "comment"]
527 ///
528 /// Default: []
529 pub edit_predictions_disabled_in: Option<Vec<String>>,
530 /// Whether to show tabs and spaces in the editor.
531 pub show_whitespaces: Option<ShowWhitespaceSetting>,
532 /// Visible characters used to render whitespace when show_whitespaces is enabled.
533 ///
534 /// Default: "•" for spaces, "→" for tabs.
535 pub whitespace_map: Option<WhitespaceMapContent>,
536 /// Whether to start a new line with a comment when a previous line is a comment as well.
537 ///
538 /// Default: true
539 pub extend_comment_on_newline: Option<bool>,
540 /// Whether to continue markdown lists when pressing enter.
541 ///
542 /// Default: true
543 pub extend_list_on_newline: Option<bool>,
544 /// Whether to indent list items when pressing tab after a list marker.
545 ///
546 /// Default: true
547 pub indent_list_on_tab: Option<bool>,
548 /// Inlay hint related settings.
549 pub inlay_hints: Option<InlayHintSettingsContent>,
550 /// Whether to automatically type closing characters for you. For example,
551 /// when you type '(', Zed will automatically add a closing ')' at the correct position.
552 ///
553 /// Default: true
554 pub use_autoclose: Option<bool>,
555 /// Whether to automatically surround text with characters for you. For example,
556 /// when you select text and type '(', Zed will automatically surround text with ().
557 ///
558 /// Default: true
559 pub use_auto_surround: Option<bool>,
560 /// Controls how the editor handles the autoclosed characters.
561 /// When set to `false`(default), skipping over and auto-removing of the closing characters
562 /// happen only for auto-inserted characters.
563 /// Otherwise(when `true`), the closing characters are always skipped over and auto-removed
564 /// no matter how they were inserted.
565 ///
566 /// Default: false
567 pub always_treat_brackets_as_autoclosed: Option<bool>,
568 /// Whether to use additional LSP queries to format (and amend) the code after
569 /// every "trigger" symbol input, defined by LSP server capabilities.
570 ///
571 /// Default: true
572 pub use_on_type_format: Option<bool>,
573 /// Which code actions to run on save before the formatter.
574 /// These are not run if formatting is off.
575 ///
576 /// Default: {} (or {"source.organizeImports": true} for Go).
577 pub code_actions_on_format: Option<HashMap<String, bool>>,
578 /// Whether to perform linked edits of associated ranges, if the language server supports it.
579 /// For example, when editing opening <html> tag, the contents of the closing </html> tag will be edited as well.
580 ///
581 /// Default: true
582 pub linked_edits: Option<bool>,
583 /// Whether indentation should be adjusted based on the context whilst typing.
584 ///
585 /// Default: true
586 pub auto_indent: Option<bool>,
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 /// Format code using Zed's Prettier integration.
938 Prettier,
939 /// Format code using an external command.
940 External {
941 /// The external program to run.
942 command: String,
943 /// The arguments to pass to the program.
944 arguments: Option<Vec<String>>,
945 },
946 /// Files should be formatted using a code action executed by language servers.
947 CodeAction(String),
948 /// Format code using a language server.
949 #[serde(untagged)]
950 LanguageServer(LanguageServerFormatterSpecifier),
951}
952
953#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
954#[serde(
955 rename_all = "snake_case",
956 // allow specifying language servers as "language_server" or {"language_server": {"name": ...}}
957 from = "LanguageServerVariantContent",
958 into = "LanguageServerVariantContent"
959)]
960pub enum LanguageServerFormatterSpecifier {
961 Specific {
962 name: String,
963 },
964 #[default]
965 Current,
966}
967
968impl From<LanguageServerVariantContent> for LanguageServerFormatterSpecifier {
969 fn from(value: LanguageServerVariantContent) -> Self {
970 match value {
971 LanguageServerVariantContent::Specific {
972 language_server: LanguageServerSpecifierContent { name: Some(name) },
973 } => Self::Specific { name },
974 _ => Self::Current,
975 }
976 }
977}
978
979impl From<LanguageServerFormatterSpecifier> for LanguageServerVariantContent {
980 fn from(value: LanguageServerFormatterSpecifier) -> Self {
981 match value {
982 LanguageServerFormatterSpecifier::Specific { name } => Self::Specific {
983 language_server: LanguageServerSpecifierContent { name: Some(name) },
984 },
985 LanguageServerFormatterSpecifier::Current => {
986 Self::Current(CurrentLanguageServerContent::LanguageServer)
987 }
988 }
989 }
990}
991
992#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
993#[serde(rename_all = "snake_case", untagged)]
994enum LanguageServerVariantContent {
995 /// Format code using a specific language server.
996 Specific {
997 language_server: LanguageServerSpecifierContent,
998 },
999 /// Format code using the current language server.
1000 Current(CurrentLanguageServerContent),
1001}
1002
1003#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
1004#[serde(rename_all = "snake_case")]
1005enum CurrentLanguageServerContent {
1006 #[default]
1007 LanguageServer,
1008}
1009
1010#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
1011#[serde(rename_all = "snake_case")]
1012struct LanguageServerSpecifierContent {
1013 /// The name of the language server to format with
1014 name: Option<String>,
1015}
1016
1017/// The settings for indent guides.
1018#[with_fallible_options]
1019#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
1020pub struct IndentGuideSettingsContent {
1021 /// Whether to display indent guides in the editor.
1022 ///
1023 /// Default: true
1024 pub enabled: Option<bool>,
1025 /// The width of the indent guides in pixels, between 1 and 10.
1026 ///
1027 /// Default: 1
1028 pub line_width: Option<u32>,
1029 /// The width of the active indent guide in pixels, between 1 and 10.
1030 ///
1031 /// Default: 1
1032 pub active_line_width: Option<u32>,
1033 /// Determines how indent guides are colored.
1034 ///
1035 /// Default: Fixed
1036 pub coloring: Option<IndentGuideColoring>,
1037 /// Determines how indent guide backgrounds are colored.
1038 ///
1039 /// Default: Disabled
1040 pub background_coloring: Option<IndentGuideBackgroundColoring>,
1041}
1042
1043/// The task settings for a particular language.
1044#[with_fallible_options]
1045#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize, JsonSchema, MergeFrom)]
1046pub struct LanguageTaskSettingsContent {
1047 /// Extra task variables to set for a particular language.
1048 pub variables: Option<HashMap<String, String>>,
1049 pub enabled: Option<bool>,
1050 /// Use LSP tasks over Zed language extension ones.
1051 /// If no LSP tasks are returned due to error/timeout or regular execution,
1052 /// Zed language extension tasks will be used instead.
1053 ///
1054 /// Other Zed tasks will still be shown:
1055 /// * Zed task from either of the task config file
1056 /// * Zed task from history (e.g. one-off task was spawned before)
1057 pub prefer_lsp: Option<bool>,
1058}
1059
1060/// Map from language name to settings.
1061#[with_fallible_options]
1062#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
1063pub struct LanguageToSettingsMap(pub HashMap<String, LanguageSettingsContent>);
1064
1065/// Determines how indent guides are colored.
1066#[derive(
1067 Default,
1068 Debug,
1069 Copy,
1070 Clone,
1071 PartialEq,
1072 Eq,
1073 Serialize,
1074 Deserialize,
1075 JsonSchema,
1076 MergeFrom,
1077 strum::VariantArray,
1078 strum::VariantNames,
1079)]
1080#[serde(rename_all = "snake_case")]
1081pub enum IndentGuideColoring {
1082 /// Do not render any lines for indent guides.
1083 Disabled,
1084 /// Use the same color for all indentation levels.
1085 #[default]
1086 Fixed,
1087 /// Use a different color for each indentation level.
1088 IndentAware,
1089}
1090
1091/// Determines how indent guide backgrounds are colored.
1092#[derive(
1093 Default,
1094 Debug,
1095 Copy,
1096 Clone,
1097 PartialEq,
1098 Eq,
1099 Serialize,
1100 Deserialize,
1101 JsonSchema,
1102 MergeFrom,
1103 strum::VariantArray,
1104 strum::VariantNames,
1105)]
1106#[serde(rename_all = "snake_case")]
1107pub enum IndentGuideBackgroundColoring {
1108 /// Do not render any background for indent guides.
1109 #[default]
1110 Disabled,
1111 /// Use a different color for each indentation level.
1112 IndentAware,
1113}
1114
1115#[cfg(test)]
1116mod test {
1117
1118 use crate::{ParseStatus, fallible_options};
1119
1120 use super::*;
1121
1122 #[test]
1123 fn test_formatter_deserialization() {
1124 let raw_auto = "{\"formatter\": \"auto\"}";
1125 let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
1126 assert_eq!(
1127 settings.formatter,
1128 Some(FormatterList::Single(Formatter::Auto))
1129 );
1130 let raw = "{\"formatter\": \"language_server\"}";
1131 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1132 assert_eq!(
1133 settings.formatter,
1134 Some(FormatterList::Single(Formatter::LanguageServer(
1135 LanguageServerFormatterSpecifier::Current
1136 )))
1137 );
1138
1139 let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
1140 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1141 assert_eq!(
1142 settings.formatter,
1143 Some(FormatterList::Vec(vec![Formatter::LanguageServer(
1144 LanguageServerFormatterSpecifier::Current
1145 )]))
1146 );
1147 let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"language_server\", \"prettier\"]}";
1148 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1149 assert_eq!(
1150 settings.formatter,
1151 Some(FormatterList::Vec(vec![
1152 Formatter::LanguageServer(LanguageServerFormatterSpecifier::Current),
1153 Formatter::LanguageServer(LanguageServerFormatterSpecifier::Current),
1154 Formatter::Prettier
1155 ]))
1156 );
1157
1158 let raw = "{\"formatter\": [{\"language_server\": {\"name\": \"ruff\"}}, \"prettier\"]}";
1159 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1160 assert_eq!(
1161 settings.formatter,
1162 Some(FormatterList::Vec(vec![
1163 Formatter::LanguageServer(LanguageServerFormatterSpecifier::Specific {
1164 name: "ruff".to_string()
1165 }),
1166 Formatter::Prettier
1167 ]))
1168 );
1169
1170 assert_eq!(
1171 serde_json::to_string(&LanguageServerFormatterSpecifier::Current).unwrap(),
1172 "\"language_server\"",
1173 );
1174 }
1175
1176 #[test]
1177 fn test_formatter_deserialization_invalid() {
1178 let raw_auto = "{\"formatter\": {}}";
1179 let (_, result) = fallible_options::parse_json::<LanguageSettingsContent>(raw_auto);
1180 assert!(matches!(result, ParseStatus::Failed { .. }));
1181 }
1182
1183 #[test]
1184 fn test_prettier_options() {
1185 let raw_prettier = r#"{"allowed": false, "tabWidth": 4, "semi": false}"#;
1186 let result = serde_json::from_str::<PrettierSettingsContent>(raw_prettier)
1187 .expect("Failed to parse prettier options");
1188 assert!(
1189 result
1190 .options
1191 .as_ref()
1192 .expect("options were flattened")
1193 .contains_key("semi")
1194 );
1195 assert!(
1196 result
1197 .options
1198 .as_ref()
1199 .expect("options were flattened")
1200 .contains_key("tabWidth")
1201 );
1202 }
1203}