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