1//! Provides `language`-related settings.
2
3use crate::{File, Language, LanguageName, LanguageServerName};
4use anyhow::Result;
5use collections::{FxHashMap, HashMap, HashSet};
6use core::slice;
7use ec4rs::{
8 Properties as EditorconfigProperties,
9 property::{FinalNewline, IndentSize, IndentStyle, TabWidth, TrimTrailingWs},
10};
11use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
12use gpui::{App, Modifiers};
13use itertools::{Either, Itertools};
14use schemars::{
15 JsonSchema,
16 schema::{InstanceType, ObjectValidation, Schema, SchemaObject, SingleOrVec},
17};
18use serde::{
19 Deserialize, Deserializer, Serialize,
20 de::{self, IntoDeserializer, MapAccess, SeqAccess, Visitor},
21};
22use serde_json::Value;
23use settings::{
24 Settings, SettingsLocation, SettingsSources, SettingsStore, add_references_to_properties,
25};
26use std::{borrow::Cow, num::NonZeroU32, path::Path, sync::Arc};
27use util::serde::default_true;
28
29/// Initializes the language settings.
30pub fn init(cx: &mut App) {
31 AllLanguageSettings::register(cx);
32}
33
34/// Returns the settings for the specified language from the provided file.
35pub fn language_settings<'a>(
36 language: Option<LanguageName>,
37 file: Option<&'a Arc<dyn File>>,
38 cx: &'a App,
39) -> Cow<'a, LanguageSettings> {
40 let location = file.map(|f| SettingsLocation {
41 worktree_id: f.worktree_id(cx),
42 path: f.path().as_ref(),
43 });
44 AllLanguageSettings::get(location, cx).language(location, language.as_ref(), cx)
45}
46
47/// Returns the settings for all languages from the provided file.
48pub fn all_language_settings<'a>(
49 file: Option<&'a Arc<dyn File>>,
50 cx: &'a App,
51) -> &'a AllLanguageSettings {
52 let location = file.map(|f| SettingsLocation {
53 worktree_id: f.worktree_id(cx),
54 path: f.path().as_ref(),
55 });
56 AllLanguageSettings::get(location, cx)
57}
58
59/// The settings for all languages.
60#[derive(Debug, Clone)]
61pub struct AllLanguageSettings {
62 /// The edit prediction settings.
63 pub edit_predictions: EditPredictionSettings,
64 pub defaults: LanguageSettings,
65 languages: HashMap<LanguageName, LanguageSettings>,
66 pub(crate) file_types: FxHashMap<Arc<str>, GlobSet>,
67}
68
69/// The settings for a particular language.
70#[derive(Debug, Clone, Deserialize)]
71pub struct LanguageSettings {
72 /// How many columns a tab should occupy.
73 pub tab_size: NonZeroU32,
74 /// Whether to indent lines using tab characters, as opposed to multiple
75 /// spaces.
76 pub hard_tabs: bool,
77 /// How to soft-wrap long lines of text.
78 pub soft_wrap: SoftWrap,
79 /// The column at which to soft-wrap lines, for buffers where soft-wrap
80 /// is enabled.
81 pub preferred_line_length: u32,
82 /// Whether to show wrap guides (vertical rulers) in the editor.
83 /// Setting this to true will show a guide at the 'preferred_line_length' value
84 /// if softwrap is set to 'preferred_line_length', and will show any
85 /// additional guides as specified by the 'wrap_guides' setting.
86 pub show_wrap_guides: bool,
87 /// Character counts at which to show wrap guides (vertical rulers) in the editor.
88 pub wrap_guides: Vec<usize>,
89 /// Indent guide related settings.
90 pub indent_guides: IndentGuideSettings,
91 /// Whether or not to perform a buffer format before saving.
92 pub format_on_save: FormatOnSave,
93 /// Whether or not to remove any trailing whitespace from lines of a buffer
94 /// before saving it.
95 pub remove_trailing_whitespace_on_save: bool,
96 /// Whether or not to ensure there's a single newline at the end of a buffer
97 /// when saving it.
98 pub ensure_final_newline_on_save: bool,
99 /// How to perform a buffer format.
100 pub formatter: SelectedFormatter,
101 /// Zed's Prettier integration settings.
102 pub prettier: PrettierSettings,
103 /// Whether to automatically close JSX tags.
104 pub jsx_tag_auto_close: JsxTagAutoCloseSettings,
105 /// Whether to use language servers to provide code intelligence.
106 pub enable_language_server: bool,
107 /// The list of language servers to use (or disable) for this language.
108 ///
109 /// This array should consist of language server IDs, as well as the following
110 /// special tokens:
111 /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
112 /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
113 pub language_servers: Vec<String>,
114 /// Controls where the `editor::Rewrap` action is allowed for this language.
115 ///
116 /// Note: This setting has no effect in Vim mode, as rewrap is already
117 /// allowed everywhere.
118 pub allow_rewrap: RewrapBehavior,
119 /// Controls whether edit predictions are shown immediately (true)
120 /// or manually by triggering `editor::ShowEditPrediction` (false).
121 pub show_edit_predictions: bool,
122 /// Controls whether edit predictions are shown in the given language
123 /// scopes.
124 pub edit_predictions_disabled_in: Vec<String>,
125 /// Whether to show tabs and spaces in the editor.
126 pub show_whitespaces: ShowWhitespaceSetting,
127 /// Whether to start a new line with a comment when a previous line is a comment as well.
128 pub extend_comment_on_newline: bool,
129 /// Inlay hint related settings.
130 pub inlay_hints: InlayHintSettings,
131 /// Whether to automatically close brackets.
132 pub use_autoclose: bool,
133 /// Whether to automatically surround text with brackets.
134 pub use_auto_surround: bool,
135 /// Whether to use additional LSP queries to format (and amend) the code after
136 /// every "trigger" symbol input, defined by LSP server capabilities.
137 pub use_on_type_format: bool,
138 /// Whether indentation of pasted content should be adjusted based on the context.
139 pub auto_indent_on_paste: bool,
140 /// Controls how the editor handles the autoclosed characters.
141 pub always_treat_brackets_as_autoclosed: bool,
142 /// Which code actions to run on save
143 pub code_actions_on_format: HashMap<String, bool>,
144 /// Whether to perform linked edits
145 pub linked_edits: bool,
146 /// Task configuration for this language.
147 pub tasks: LanguageTaskConfig,
148 /// Whether to pop the completions menu while typing in an editor without
149 /// explicitly requesting it.
150 pub show_completions_on_input: bool,
151 /// Whether to display inline and alongside documentation for items in the
152 /// completions menu.
153 pub show_completion_documentation: bool,
154 /// Completion settings for this language.
155 pub completions: CompletionSettings,
156 /// Preferred debuggers for this language.
157 pub debuggers: Vec<String>,
158}
159
160impl LanguageSettings {
161 /// A token representing the rest of the available language servers.
162 const REST_OF_LANGUAGE_SERVERS: &'static str = "...";
163
164 /// Returns the customized list of language servers from the list of
165 /// available language servers.
166 pub fn customized_language_servers(
167 &self,
168 available_language_servers: &[LanguageServerName],
169 ) -> Vec<LanguageServerName> {
170 Self::resolve_language_servers(&self.language_servers, available_language_servers)
171 }
172
173 pub(crate) fn resolve_language_servers(
174 configured_language_servers: &[String],
175 available_language_servers: &[LanguageServerName],
176 ) -> Vec<LanguageServerName> {
177 let (disabled_language_servers, enabled_language_servers): (
178 Vec<LanguageServerName>,
179 Vec<LanguageServerName>,
180 ) = configured_language_servers.iter().partition_map(
181 |language_server| match language_server.strip_prefix('!') {
182 Some(disabled) => Either::Left(LanguageServerName(disabled.to_string().into())),
183 None => Either::Right(LanguageServerName(language_server.clone().into())),
184 },
185 );
186
187 let rest = available_language_servers
188 .iter()
189 .filter(|&available_language_server| {
190 !disabled_language_servers.contains(&available_language_server)
191 && !enabled_language_servers.contains(&available_language_server)
192 })
193 .cloned()
194 .collect::<Vec<_>>();
195
196 enabled_language_servers
197 .into_iter()
198 .flat_map(|language_server| {
199 if language_server.0.as_ref() == Self::REST_OF_LANGUAGE_SERVERS {
200 rest.clone()
201 } else {
202 vec![language_server.clone()]
203 }
204 })
205 .collect::<Vec<_>>()
206 }
207}
208
209/// The provider that supplies edit predictions.
210#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
211#[serde(rename_all = "snake_case")]
212pub enum EditPredictionProvider {
213 None,
214 #[default]
215 Copilot,
216 Supermaven,
217 Zed,
218}
219
220impl EditPredictionProvider {
221 pub fn is_zed(&self) -> bool {
222 match self {
223 EditPredictionProvider::Zed => true,
224 EditPredictionProvider::None
225 | EditPredictionProvider::Copilot
226 | EditPredictionProvider::Supermaven => false,
227 }
228 }
229}
230
231/// The settings for edit predictions, such as [GitHub Copilot](https://github.com/features/copilot)
232/// or [Supermaven](https://supermaven.com).
233#[derive(Clone, Debug, Default)]
234pub struct EditPredictionSettings {
235 /// The provider that supplies edit predictions.
236 pub provider: EditPredictionProvider,
237 /// A list of globs representing files that edit predictions should be disabled for.
238 /// This list adds to a pre-existing, sensible default set of globs.
239 /// Any additional ones you add are combined with them.
240 pub disabled_globs: Vec<DisabledGlob>,
241 /// Configures how edit predictions are displayed in the buffer.
242 pub mode: EditPredictionsMode,
243 /// Settings specific to GitHub Copilot.
244 pub copilot: CopilotSettings,
245 /// Whether edit predictions are enabled in the assistant panel.
246 /// This setting has no effect if globally disabled.
247 pub enabled_in_text_threads: bool,
248}
249
250impl EditPredictionSettings {
251 /// Returns whether edit predictions are enabled for the given path.
252 pub fn enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
253 !self.disabled_globs.iter().any(|glob| {
254 if glob.is_absolute {
255 file.as_local()
256 .map_or(false, |local| glob.matcher.is_match(local.abs_path(cx)))
257 } else {
258 glob.matcher.is_match(file.path())
259 }
260 })
261 }
262}
263
264#[derive(Clone, Debug)]
265pub struct DisabledGlob {
266 matcher: GlobMatcher,
267 is_absolute: bool,
268}
269
270/// The mode in which edit predictions should be displayed.
271#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
272#[serde(rename_all = "snake_case")]
273pub enum EditPredictionsMode {
274 /// If provider supports it, display inline when holding modifier key (e.g., alt).
275 /// Otherwise, eager preview is used.
276 #[serde(alias = "auto")]
277 Subtle,
278 /// Display inline when there are no language server completions available.
279 #[default]
280 #[serde(alias = "eager_preview")]
281 Eager,
282}
283
284#[derive(Clone, Debug, Default)]
285pub struct CopilotSettings {
286 /// HTTP/HTTPS proxy to use for Copilot.
287 pub proxy: Option<String>,
288 /// Disable certificate verification for proxy (not recommended).
289 pub proxy_no_verify: Option<bool>,
290}
291
292/// The settings for all languages.
293#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
294pub struct AllLanguageSettingsContent {
295 /// The settings for enabling/disabling features.
296 #[serde(default)]
297 pub features: Option<FeaturesContent>,
298 /// The edit prediction settings.
299 #[serde(default)]
300 pub edit_predictions: Option<EditPredictionSettingsContent>,
301 /// The default language settings.
302 #[serde(flatten)]
303 pub defaults: LanguageSettingsContent,
304 /// The settings for individual languages.
305 #[serde(default)]
306 pub languages: HashMap<LanguageName, LanguageSettingsContent>,
307 /// Settings for associating file extensions and filenames
308 /// with languages.
309 #[serde(default)]
310 pub file_types: HashMap<Arc<str>, Vec<String>>,
311}
312
313/// Controls how completions are processed for this language.
314#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
315#[serde(rename_all = "snake_case")]
316pub struct CompletionSettings {
317 /// Controls how words are completed.
318 /// For large documents, not all words may be fetched for completion.
319 ///
320 /// Default: `fallback`
321 #[serde(default = "default_words_completion_mode")]
322 pub words: WordsCompletionMode,
323 /// Whether to fetch LSP completions or not.
324 ///
325 /// Default: true
326 #[serde(default = "default_true")]
327 pub lsp: bool,
328 /// When fetching LSP completions, determines how long to wait for a response of a particular server.
329 /// When set to 0, waits indefinitely.
330 ///
331 /// Default: 0
332 #[serde(default = "default_lsp_fetch_timeout_ms")]
333 pub lsp_fetch_timeout_ms: u64,
334 /// Controls how LSP completions are inserted.
335 ///
336 /// Default: "replace_suffix"
337 #[serde(default = "default_lsp_insert_mode")]
338 pub lsp_insert_mode: LspInsertMode,
339}
340
341/// Controls how document's words are completed.
342#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
343#[serde(rename_all = "snake_case")]
344pub enum WordsCompletionMode {
345 /// Always fetch document's words for completions along with LSP completions.
346 Enabled,
347 /// Only if LSP response errors or times out,
348 /// use document's words to show completions.
349 Fallback,
350 /// Never fetch or complete document's words for completions.
351 /// (Word-based completions can still be queried via a separate action)
352 Disabled,
353}
354
355#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
356#[serde(rename_all = "snake_case")]
357pub enum LspInsertMode {
358 /// Replaces text before the cursor, using the `insert` range described in the LSP specification.
359 Insert,
360 /// Replaces text before and after the cursor, using the `replace` range described in the LSP specification.
361 Replace,
362 /// Behaves like `"replace"` if the text that would be replaced is a subsequence of the completion text,
363 /// and like `"insert"` otherwise.
364 ReplaceSubsequence,
365 /// Behaves like `"replace"` if the text after the cursor is a suffix of the completion, and like
366 /// `"insert"` otherwise.
367 ReplaceSuffix,
368}
369
370fn default_words_completion_mode() -> WordsCompletionMode {
371 WordsCompletionMode::Fallback
372}
373
374fn default_lsp_insert_mode() -> LspInsertMode {
375 LspInsertMode::ReplaceSuffix
376}
377
378fn default_lsp_fetch_timeout_ms() -> u64 {
379 0
380}
381
382/// The settings for a particular language.
383#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
384#[schemars(deny_unknown_fields)]
385pub struct LanguageSettingsContent {
386 /// How many columns a tab should occupy.
387 ///
388 /// Default: 4
389 #[serde(default)]
390 pub tab_size: Option<NonZeroU32>,
391 /// Whether to indent lines using tab characters, as opposed to multiple
392 /// spaces.
393 ///
394 /// Default: false
395 #[serde(default)]
396 pub hard_tabs: Option<bool>,
397 /// How to soft-wrap long lines of text.
398 ///
399 /// Default: none
400 #[serde(default)]
401 pub soft_wrap: Option<SoftWrap>,
402 /// The column at which to soft-wrap lines, for buffers where soft-wrap
403 /// is enabled.
404 ///
405 /// Default: 80
406 #[serde(default)]
407 pub preferred_line_length: Option<u32>,
408 /// Whether to show wrap guides in the editor. Setting this to true will
409 /// show a guide at the 'preferred_line_length' value if softwrap is set to
410 /// 'preferred_line_length', and will show any additional guides as specified
411 /// by the 'wrap_guides' setting.
412 ///
413 /// Default: true
414 #[serde(default)]
415 pub show_wrap_guides: Option<bool>,
416 /// Character counts at which to show wrap guides in the editor.
417 ///
418 /// Default: []
419 #[serde(default)]
420 pub wrap_guides: Option<Vec<usize>>,
421 /// Indent guide related settings.
422 #[serde(default)]
423 pub indent_guides: Option<IndentGuideSettings>,
424 /// Whether or not to perform a buffer format before saving.
425 ///
426 /// Default: on
427 #[serde(default)]
428 pub format_on_save: Option<FormatOnSave>,
429 /// Whether or not to remove any trailing whitespace from lines of a buffer
430 /// before saving it.
431 ///
432 /// Default: true
433 #[serde(default)]
434 pub remove_trailing_whitespace_on_save: Option<bool>,
435 /// Whether or not to ensure there's a single newline at the end of a buffer
436 /// when saving it.
437 ///
438 /// Default: true
439 #[serde(default)]
440 pub ensure_final_newline_on_save: Option<bool>,
441 /// How to perform a buffer format.
442 ///
443 /// Default: auto
444 #[serde(default)]
445 pub formatter: Option<SelectedFormatter>,
446 /// Zed's Prettier integration settings.
447 /// Allows to enable/disable formatting with Prettier
448 /// and configure default Prettier, used when no project-level Prettier installation is found.
449 ///
450 /// Default: off
451 #[serde(default)]
452 pub prettier: Option<PrettierSettings>,
453 /// Whether to automatically close JSX tags.
454 #[serde(default)]
455 pub jsx_tag_auto_close: Option<JsxTagAutoCloseSettings>,
456 /// Whether to use language servers to provide code intelligence.
457 ///
458 /// Default: true
459 #[serde(default)]
460 pub enable_language_server: Option<bool>,
461 /// The list of language servers to use (or disable) for this language.
462 ///
463 /// This array should consist of language server IDs, as well as the following
464 /// special tokens:
465 /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
466 /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
467 ///
468 /// Default: ["..."]
469 #[serde(default)]
470 pub language_servers: Option<Vec<String>>,
471 /// Controls where the `editor::Rewrap` action is allowed for this language.
472 ///
473 /// Note: This setting has no effect in Vim mode, as rewrap is already
474 /// allowed everywhere.
475 ///
476 /// Default: "in_comments"
477 #[serde(default)]
478 pub allow_rewrap: Option<RewrapBehavior>,
479 /// Controls whether edit predictions are shown immediately (true)
480 /// or manually by triggering `editor::ShowEditPrediction` (false).
481 ///
482 /// Default: true
483 #[serde(default)]
484 pub show_edit_predictions: Option<bool>,
485 /// Controls whether edit predictions are shown in the given language
486 /// scopes.
487 ///
488 /// Example: ["string", "comment"]
489 ///
490 /// Default: []
491 #[serde(default)]
492 pub edit_predictions_disabled_in: Option<Vec<String>>,
493 /// Whether to show tabs and spaces in the editor.
494 #[serde(default)]
495 pub show_whitespaces: Option<ShowWhitespaceSetting>,
496 /// Whether to start a new line with a comment when a previous line is a comment as well.
497 ///
498 /// Default: true
499 #[serde(default)]
500 pub extend_comment_on_newline: Option<bool>,
501 /// Inlay hint related settings.
502 #[serde(default)]
503 pub inlay_hints: Option<InlayHintSettings>,
504 /// Whether to automatically type closing characters for you. For example,
505 /// when you type (, Zed will automatically add a closing ) at the correct position.
506 ///
507 /// Default: true
508 pub use_autoclose: Option<bool>,
509 /// Whether to automatically surround text with characters for you. For example,
510 /// when you select text and type (, Zed will automatically surround text with ().
511 ///
512 /// Default: true
513 pub use_auto_surround: Option<bool>,
514 /// Controls how the editor handles the autoclosed characters.
515 /// When set to `false`(default), skipping over and auto-removing of the closing characters
516 /// happen only for auto-inserted characters.
517 /// Otherwise(when `true`), the closing characters are always skipped over and auto-removed
518 /// no matter how they were inserted.
519 ///
520 /// Default: false
521 pub always_treat_brackets_as_autoclosed: Option<bool>,
522 /// Whether to use additional LSP queries to format (and amend) the code after
523 /// every "trigger" symbol input, defined by LSP server capabilities.
524 ///
525 /// Default: true
526 pub use_on_type_format: Option<bool>,
527 /// Which code actions to run on save after the formatter.
528 /// These are not run if formatting is off.
529 ///
530 /// Default: {} (or {"source.organizeImports": true} for Go).
531 pub code_actions_on_format: Option<HashMap<String, bool>>,
532 /// Whether to perform linked edits of associated ranges, if the language server supports it.
533 /// For example, when editing opening <html> tag, the contents of the closing </html> tag will be edited as well.
534 ///
535 /// Default: true
536 pub linked_edits: Option<bool>,
537 /// Whether indentation of pasted content should be adjusted based on the context.
538 ///
539 /// Default: true
540 pub auto_indent_on_paste: Option<bool>,
541 /// Task configuration for this language.
542 ///
543 /// Default: {}
544 pub tasks: Option<LanguageTaskConfig>,
545 /// Whether to pop the completions menu while typing in an editor without
546 /// explicitly requesting it.
547 ///
548 /// Default: true
549 pub show_completions_on_input: Option<bool>,
550 /// Whether to display inline and alongside documentation for items in the
551 /// completions menu.
552 ///
553 /// Default: true
554 pub show_completion_documentation: Option<bool>,
555 /// Controls how completions are processed for this language.
556 pub completions: Option<CompletionSettings>,
557 /// Preferred debuggers for this language.
558 ///
559 /// Default: []
560 pub debuggers: Option<Vec<String>>,
561}
562
563/// The behavior of `editor::Rewrap`.
564#[derive(Debug, PartialEq, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]
565#[serde(rename_all = "snake_case")]
566pub enum RewrapBehavior {
567 /// Only rewrap within comments.
568 #[default]
569 InComments,
570 /// Only rewrap within the current selection(s).
571 InSelections,
572 /// Allow rewrapping anywhere.
573 Anywhere,
574}
575
576/// The contents of the edit prediction settings.
577#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)]
578pub struct EditPredictionSettingsContent {
579 /// A list of globs representing files that edit predictions should be disabled for.
580 /// This list adds to a pre-existing, sensible default set of globs.
581 /// Any additional ones you add are combined with them.
582 #[serde(default)]
583 pub disabled_globs: Option<Vec<String>>,
584 /// The mode used to display edit predictions in the buffer.
585 /// Provider support required.
586 #[serde(default)]
587 pub mode: EditPredictionsMode,
588 /// Settings specific to GitHub Copilot.
589 #[serde(default)]
590 pub copilot: CopilotSettingsContent,
591 /// Whether edit predictions are enabled in the assistant prompt editor.
592 /// This has no effect if globally disabled.
593 #[serde(default = "default_true")]
594 pub enabled_in_text_threads: bool,
595}
596
597#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)]
598pub struct CopilotSettingsContent {
599 /// HTTP/HTTPS proxy to use for Copilot.
600 ///
601 /// Default: none
602 #[serde(default)]
603 pub proxy: Option<String>,
604 /// Disable certificate verification for the proxy (not recommended).
605 ///
606 /// Default: false
607 #[serde(default)]
608 pub proxy_no_verify: Option<bool>,
609}
610
611/// The settings for enabling/disabling features.
612#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
613#[serde(rename_all = "snake_case")]
614pub struct FeaturesContent {
615 /// Determines which edit prediction provider to use.
616 pub edit_prediction_provider: Option<EditPredictionProvider>,
617}
618
619/// Controls the soft-wrapping behavior in the editor.
620#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
621#[serde(rename_all = "snake_case")]
622pub enum SoftWrap {
623 /// Prefer a single line generally, unless an overly long line is encountered.
624 None,
625 /// Deprecated: use None instead. Left to avoid breaking existing users' configs.
626 /// Prefer a single line generally, unless an overly long line is encountered.
627 PreferLine,
628 /// Soft wrap lines that exceed the editor width.
629 EditorWidth,
630 /// Soft wrap lines at the preferred line length.
631 PreferredLineLength,
632 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
633 Bounded,
634}
635
636/// Controls the behavior of formatting files when they are saved.
637#[derive(Debug, Clone, PartialEq, Eq)]
638pub enum FormatOnSave {
639 /// Files should be formatted on save.
640 On,
641 /// Files should not be formatted on save.
642 Off,
643 List(FormatterList),
644}
645
646impl JsonSchema for FormatOnSave {
647 fn schema_name() -> String {
648 "OnSaveFormatter".into()
649 }
650
651 fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> Schema {
652 let mut schema = SchemaObject::default();
653 let formatter_schema = Formatter::json_schema(generator);
654 schema.instance_type = Some(
655 vec![
656 InstanceType::Object,
657 InstanceType::String,
658 InstanceType::Array,
659 ]
660 .into(),
661 );
662
663 let valid_raw_values = SchemaObject {
664 enum_values: Some(vec![
665 Value::String("on".into()),
666 Value::String("off".into()),
667 Value::String("prettier".into()),
668 Value::String("language_server".into()),
669 ]),
670 ..Default::default()
671 };
672 let mut nested_values = SchemaObject::default();
673
674 nested_values.array().items = Some(formatter_schema.clone().into());
675
676 schema.subschemas().any_of = Some(vec![
677 nested_values.into(),
678 valid_raw_values.into(),
679 formatter_schema,
680 ]);
681 schema.into()
682 }
683}
684
685impl Serialize for FormatOnSave {
686 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
687 where
688 S: serde::Serializer,
689 {
690 match self {
691 Self::On => serializer.serialize_str("on"),
692 Self::Off => serializer.serialize_str("off"),
693 Self::List(list) => list.serialize(serializer),
694 }
695 }
696}
697
698impl<'de> Deserialize<'de> for FormatOnSave {
699 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
700 where
701 D: Deserializer<'de>,
702 {
703 struct FormatDeserializer;
704
705 impl<'d> Visitor<'d> for FormatDeserializer {
706 type Value = FormatOnSave;
707
708 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
709 formatter.write_str("a valid on-save formatter kind")
710 }
711 fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
712 where
713 E: serde::de::Error,
714 {
715 if v == "on" {
716 Ok(Self::Value::On)
717 } else if v == "off" {
718 Ok(Self::Value::Off)
719 } else if v == "language_server" {
720 Ok(Self::Value::List(FormatterList(
721 Formatter::LanguageServer { name: None }.into(),
722 )))
723 } else {
724 let ret: Result<FormatterList, _> =
725 Deserialize::deserialize(v.into_deserializer());
726 ret.map(Self::Value::List)
727 }
728 }
729 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
730 where
731 A: MapAccess<'d>,
732 {
733 let ret: Result<FormatterList, _> =
734 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
735 ret.map(Self::Value::List)
736 }
737 fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
738 where
739 A: SeqAccess<'d>,
740 {
741 let ret: Result<FormatterList, _> =
742 Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
743 ret.map(Self::Value::List)
744 }
745 }
746 deserializer.deserialize_any(FormatDeserializer)
747 }
748}
749
750/// Controls how whitespace should be displayedin the editor.
751#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
752#[serde(rename_all = "snake_case")]
753pub enum ShowWhitespaceSetting {
754 /// Draw whitespace only for the selected text.
755 Selection,
756 /// Do not draw any tabs or spaces.
757 None,
758 /// Draw all invisible symbols.
759 All,
760 /// Draw whitespaces at boundaries only.
761 ///
762 /// For a whitespace to be on a boundary, any of the following conditions need to be met:
763 /// - It is a tab
764 /// - It is adjacent to an edge (start or end)
765 /// - It is adjacent to a whitespace (left or right)
766 Boundary,
767}
768
769/// Controls which formatter should be used when formatting code.
770#[derive(Clone, Debug, Default, PartialEq, Eq)]
771pub enum SelectedFormatter {
772 /// Format files using Zed's Prettier integration (if applicable),
773 /// or falling back to formatting via language server.
774 #[default]
775 Auto,
776 List(FormatterList),
777}
778
779impl JsonSchema for SelectedFormatter {
780 fn schema_name() -> String {
781 "Formatter".into()
782 }
783
784 fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> Schema {
785 let mut schema = SchemaObject::default();
786 let formatter_schema = Formatter::json_schema(generator);
787 schema.instance_type = Some(
788 vec![
789 InstanceType::Object,
790 InstanceType::String,
791 InstanceType::Array,
792 ]
793 .into(),
794 );
795
796 let valid_raw_values = SchemaObject {
797 enum_values: Some(vec![
798 Value::String("auto".into()),
799 Value::String("prettier".into()),
800 Value::String("language_server".into()),
801 ]),
802 ..Default::default()
803 };
804
805 let mut nested_values = SchemaObject::default();
806
807 nested_values.array().items = Some(formatter_schema.clone().into());
808
809 schema.subschemas().any_of = Some(vec![
810 nested_values.into(),
811 valid_raw_values.into(),
812 formatter_schema,
813 ]);
814 schema.into()
815 }
816}
817
818impl Serialize for SelectedFormatter {
819 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
820 where
821 S: serde::Serializer,
822 {
823 match self {
824 SelectedFormatter::Auto => serializer.serialize_str("auto"),
825 SelectedFormatter::List(list) => list.serialize(serializer),
826 }
827 }
828}
829impl<'de> Deserialize<'de> for SelectedFormatter {
830 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
831 where
832 D: Deserializer<'de>,
833 {
834 struct FormatDeserializer;
835
836 impl<'d> Visitor<'d> for FormatDeserializer {
837 type Value = SelectedFormatter;
838
839 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
840 formatter.write_str("a valid formatter kind")
841 }
842 fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
843 where
844 E: serde::de::Error,
845 {
846 if v == "auto" {
847 Ok(Self::Value::Auto)
848 } else if v == "language_server" {
849 Ok(Self::Value::List(FormatterList(
850 Formatter::LanguageServer { name: None }.into(),
851 )))
852 } else {
853 let ret: Result<FormatterList, _> =
854 Deserialize::deserialize(v.into_deserializer());
855 ret.map(SelectedFormatter::List)
856 }
857 }
858 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
859 where
860 A: MapAccess<'d>,
861 {
862 let ret: Result<FormatterList, _> =
863 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
864 ret.map(SelectedFormatter::List)
865 }
866 fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
867 where
868 A: SeqAccess<'d>,
869 {
870 let ret: Result<FormatterList, _> =
871 Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
872 ret.map(SelectedFormatter::List)
873 }
874 }
875 deserializer.deserialize_any(FormatDeserializer)
876 }
877}
878/// Controls which formatter should be used when formatting code.
879#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
880#[serde(rename_all = "snake_case", transparent)]
881pub struct FormatterList(pub SingleOrVec<Formatter>);
882
883impl AsRef<[Formatter]> for FormatterList {
884 fn as_ref(&self) -> &[Formatter] {
885 match &self.0 {
886 SingleOrVec::Single(single) => slice::from_ref(single),
887 SingleOrVec::Vec(v) => v,
888 }
889 }
890}
891
892/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
893#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
894#[serde(rename_all = "snake_case")]
895pub enum Formatter {
896 /// Format code using the current language server.
897 LanguageServer { name: Option<String> },
898 /// Format code using Zed's Prettier integration.
899 Prettier,
900 /// Format code using an external command.
901 External {
902 /// The external program to run.
903 command: Arc<str>,
904 /// The arguments to pass to the program.
905 arguments: Option<Arc<[String]>>,
906 },
907 /// Files should be formatted using code actions executed by language servers.
908 CodeActions(HashMap<String, bool>),
909}
910
911/// The settings for indent guides.
912#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
913pub struct IndentGuideSettings {
914 /// Whether to display indent guides in the editor.
915 ///
916 /// Default: true
917 #[serde(default = "default_true")]
918 pub enabled: bool,
919 /// The width of the indent guides in pixels, between 1 and 10.
920 ///
921 /// Default: 1
922 #[serde(default = "line_width")]
923 pub line_width: u32,
924 /// The width of the active indent guide in pixels, between 1 and 10.
925 ///
926 /// Default: 1
927 #[serde(default = "active_line_width")]
928 pub active_line_width: u32,
929 /// Determines how indent guides are colored.
930 ///
931 /// Default: Fixed
932 #[serde(default)]
933 pub coloring: IndentGuideColoring,
934 /// Determines how indent guide backgrounds are colored.
935 ///
936 /// Default: Disabled
937 #[serde(default)]
938 pub background_coloring: IndentGuideBackgroundColoring,
939}
940
941fn line_width() -> u32 {
942 1
943}
944
945fn active_line_width() -> u32 {
946 line_width()
947}
948
949/// Determines how indent guides are colored.
950#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
951#[serde(rename_all = "snake_case")]
952pub enum IndentGuideColoring {
953 /// Do not render any lines for indent guides.
954 Disabled,
955 /// Use the same color for all indentation levels.
956 #[default]
957 Fixed,
958 /// Use a different color for each indentation level.
959 IndentAware,
960}
961
962/// Determines how indent guide backgrounds are colored.
963#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
964#[serde(rename_all = "snake_case")]
965pub enum IndentGuideBackgroundColoring {
966 /// Do not render any background for indent guides.
967 #[default]
968 Disabled,
969 /// Use a different color for each indentation level.
970 IndentAware,
971}
972
973/// The settings for inlay hints.
974#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
975pub struct InlayHintSettings {
976 /// Global switch to toggle hints on and off.
977 ///
978 /// Default: false
979 #[serde(default)]
980 pub enabled: bool,
981 /// Global switch to toggle inline values on and off.
982 ///
983 /// Default: true
984 #[serde(default = "default_true")]
985 pub show_value_hints: bool,
986 /// Whether type hints should be shown.
987 ///
988 /// Default: true
989 #[serde(default = "default_true")]
990 pub show_type_hints: bool,
991 /// Whether parameter hints should be shown.
992 ///
993 /// Default: true
994 #[serde(default = "default_true")]
995 pub show_parameter_hints: bool,
996 /// Whether other hints should be shown.
997 ///
998 /// Default: true
999 #[serde(default = "default_true")]
1000 pub show_other_hints: bool,
1001 /// Whether to show a background for inlay hints.
1002 ///
1003 /// If set to `true`, the background will use the `hint.background` color
1004 /// from the current theme.
1005 ///
1006 /// Default: false
1007 #[serde(default)]
1008 pub show_background: bool,
1009 /// Whether or not to debounce inlay hints updates after buffer edits.
1010 ///
1011 /// Set to 0 to disable debouncing.
1012 ///
1013 /// Default: 700
1014 #[serde(default = "edit_debounce_ms")]
1015 pub edit_debounce_ms: u64,
1016 /// Whether or not to debounce inlay hints updates after buffer scrolls.
1017 ///
1018 /// Set to 0 to disable debouncing.
1019 ///
1020 /// Default: 50
1021 #[serde(default = "scroll_debounce_ms")]
1022 pub scroll_debounce_ms: u64,
1023 /// Toggles inlay hints (hides or shows) when the user presses the modifiers specified.
1024 /// If only a subset of the modifiers specified is pressed, hints are not toggled.
1025 /// If no modifiers are specified, this is equivalent to `None`.
1026 ///
1027 /// Default: None
1028 #[serde(default)]
1029 pub toggle_on_modifiers_press: Option<Modifiers>,
1030}
1031
1032fn edit_debounce_ms() -> u64 {
1033 700
1034}
1035
1036fn scroll_debounce_ms() -> u64 {
1037 50
1038}
1039
1040/// The task settings for a particular language.
1041#[derive(Debug, Clone, Deserialize, PartialEq, Serialize, JsonSchema)]
1042pub struct LanguageTaskConfig {
1043 /// Extra task variables to set for a particular language.
1044 #[serde(default)]
1045 pub variables: HashMap<String, String>,
1046 #[serde(default = "default_true")]
1047 pub enabled: bool,
1048}
1049
1050impl InlayHintSettings {
1051 /// Returns the kinds of inlay hints that are enabled based on the settings.
1052 pub fn enabled_inlay_hint_kinds(&self) -> HashSet<Option<InlayHintKind>> {
1053 let mut kinds = HashSet::default();
1054 if self.show_type_hints {
1055 kinds.insert(Some(InlayHintKind::Type));
1056 }
1057 if self.show_parameter_hints {
1058 kinds.insert(Some(InlayHintKind::Parameter));
1059 }
1060 if self.show_other_hints {
1061 kinds.insert(None);
1062 }
1063 kinds
1064 }
1065}
1066
1067impl AllLanguageSettings {
1068 /// Returns the [`LanguageSettings`] for the language with the specified name.
1069 pub fn language<'a>(
1070 &'a self,
1071 location: Option<SettingsLocation<'a>>,
1072 language_name: Option<&LanguageName>,
1073 cx: &'a App,
1074 ) -> Cow<'a, LanguageSettings> {
1075 let settings = language_name
1076 .and_then(|name| self.languages.get(name))
1077 .unwrap_or(&self.defaults);
1078
1079 let editorconfig_properties = location.and_then(|location| {
1080 cx.global::<SettingsStore>()
1081 .editorconfig_properties(location.worktree_id, location.path)
1082 });
1083 if let Some(editorconfig_properties) = editorconfig_properties {
1084 let mut settings = settings.clone();
1085 merge_with_editorconfig(&mut settings, &editorconfig_properties);
1086 Cow::Owned(settings)
1087 } else {
1088 Cow::Borrowed(settings)
1089 }
1090 }
1091
1092 /// Returns whether edit predictions are enabled for the given path.
1093 pub fn edit_predictions_enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
1094 self.edit_predictions.enabled_for_file(file, cx)
1095 }
1096
1097 /// Returns whether edit predictions are enabled for the given language and path.
1098 pub fn show_edit_predictions(&self, language: Option<&Arc<Language>>, cx: &App) -> bool {
1099 self.language(None, language.map(|l| l.name()).as_ref(), cx)
1100 .show_edit_predictions
1101 }
1102
1103 /// Returns the edit predictions preview mode for the given language and path.
1104 pub fn edit_predictions_mode(&self) -> EditPredictionsMode {
1105 self.edit_predictions.mode
1106 }
1107}
1108
1109fn merge_with_editorconfig(settings: &mut LanguageSettings, cfg: &EditorconfigProperties) {
1110 let tab_size = cfg.get::<IndentSize>().ok().and_then(|v| match v {
1111 IndentSize::Value(u) => NonZeroU32::new(u as u32),
1112 IndentSize::UseTabWidth => cfg.get::<TabWidth>().ok().and_then(|w| match w {
1113 TabWidth::Value(u) => NonZeroU32::new(u as u32),
1114 }),
1115 });
1116 let hard_tabs = cfg
1117 .get::<IndentStyle>()
1118 .map(|v| v.eq(&IndentStyle::Tabs))
1119 .ok();
1120 let ensure_final_newline_on_save = cfg
1121 .get::<FinalNewline>()
1122 .map(|v| match v {
1123 FinalNewline::Value(b) => b,
1124 })
1125 .ok();
1126 let remove_trailing_whitespace_on_save = cfg
1127 .get::<TrimTrailingWs>()
1128 .map(|v| match v {
1129 TrimTrailingWs::Value(b) => b,
1130 })
1131 .ok();
1132 fn merge<T>(target: &mut T, value: Option<T>) {
1133 if let Some(value) = value {
1134 *target = value;
1135 }
1136 }
1137 merge(&mut settings.tab_size, tab_size);
1138 merge(&mut settings.hard_tabs, hard_tabs);
1139 merge(
1140 &mut settings.remove_trailing_whitespace_on_save,
1141 remove_trailing_whitespace_on_save,
1142 );
1143 merge(
1144 &mut settings.ensure_final_newline_on_save,
1145 ensure_final_newline_on_save,
1146 );
1147}
1148
1149/// The kind of an inlay hint.
1150#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1151pub enum InlayHintKind {
1152 /// An inlay hint for a type.
1153 Type,
1154 /// An inlay hint for a parameter.
1155 Parameter,
1156}
1157
1158impl InlayHintKind {
1159 /// Returns the [`InlayHintKind`] from the given name.
1160 ///
1161 /// Returns `None` if `name` does not match any of the expected
1162 /// string representations.
1163 pub fn from_name(name: &str) -> Option<Self> {
1164 match name {
1165 "type" => Some(InlayHintKind::Type),
1166 "parameter" => Some(InlayHintKind::Parameter),
1167 _ => None,
1168 }
1169 }
1170
1171 /// Returns the name of this [`InlayHintKind`].
1172 pub fn name(&self) -> &'static str {
1173 match self {
1174 InlayHintKind::Type => "type",
1175 InlayHintKind::Parameter => "parameter",
1176 }
1177 }
1178}
1179
1180impl settings::Settings for AllLanguageSettings {
1181 const KEY: Option<&'static str> = None;
1182
1183 type FileContent = AllLanguageSettingsContent;
1184
1185 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1186 let default_value = sources.default;
1187
1188 // A default is provided for all settings.
1189 let mut defaults: LanguageSettings =
1190 serde_json::from_value(serde_json::to_value(&default_value.defaults)?)?;
1191
1192 let mut languages = HashMap::default();
1193 for (language_name, settings) in &default_value.languages {
1194 let mut language_settings = defaults.clone();
1195 merge_settings(&mut language_settings, settings);
1196 languages.insert(language_name.clone(), language_settings);
1197 }
1198
1199 let mut edit_prediction_provider = default_value
1200 .features
1201 .as_ref()
1202 .and_then(|f| f.edit_prediction_provider);
1203 let mut edit_predictions_mode = default_value
1204 .edit_predictions
1205 .as_ref()
1206 .map(|edit_predictions| edit_predictions.mode)
1207 .ok_or_else(Self::missing_default)?;
1208
1209 let mut completion_globs: HashSet<&String> = default_value
1210 .edit_predictions
1211 .as_ref()
1212 .and_then(|c| c.disabled_globs.as_ref())
1213 .map(|globs| globs.iter().collect())
1214 .ok_or_else(Self::missing_default)?;
1215
1216 let mut copilot_settings = default_value
1217 .edit_predictions
1218 .as_ref()
1219 .map(|settings| settings.copilot.clone())
1220 .map(|copilot| CopilotSettings {
1221 proxy: copilot.proxy,
1222 proxy_no_verify: copilot.proxy_no_verify,
1223 })
1224 .unwrap_or_default();
1225
1226 let mut enabled_in_text_threads = default_value
1227 .edit_predictions
1228 .as_ref()
1229 .map(|settings| settings.enabled_in_text_threads)
1230 .unwrap_or(true);
1231
1232 let mut file_types: FxHashMap<Arc<str>, GlobSet> = FxHashMap::default();
1233
1234 for (language, patterns) in &default_value.file_types {
1235 let mut builder = GlobSetBuilder::new();
1236
1237 for pattern in patterns {
1238 builder.add(Glob::new(pattern)?);
1239 }
1240
1241 file_types.insert(language.clone(), builder.build()?);
1242 }
1243
1244 for user_settings in sources.customizations() {
1245 if let Some(provider) = user_settings
1246 .features
1247 .as_ref()
1248 .and_then(|f| f.edit_prediction_provider)
1249 {
1250 edit_prediction_provider = Some(provider);
1251 }
1252
1253 if let Some(edit_predictions) = user_settings.edit_predictions.as_ref() {
1254 edit_predictions_mode = edit_predictions.mode;
1255 enabled_in_text_threads = edit_predictions.enabled_in_text_threads;
1256
1257 if let Some(disabled_globs) = edit_predictions.disabled_globs.as_ref() {
1258 completion_globs.extend(disabled_globs.iter());
1259 }
1260 }
1261
1262 if let Some(proxy) = user_settings
1263 .edit_predictions
1264 .as_ref()
1265 .and_then(|settings| settings.copilot.proxy.clone())
1266 {
1267 copilot_settings.proxy = Some(proxy);
1268 }
1269
1270 if let Some(proxy_no_verify) = user_settings
1271 .edit_predictions
1272 .as_ref()
1273 .and_then(|settings| settings.copilot.proxy_no_verify)
1274 {
1275 copilot_settings.proxy_no_verify = Some(proxy_no_verify);
1276 }
1277
1278 // A user's global settings override the default global settings and
1279 // all default language-specific settings.
1280 merge_settings(&mut defaults, &user_settings.defaults);
1281 for language_settings in languages.values_mut() {
1282 merge_settings(language_settings, &user_settings.defaults);
1283 }
1284
1285 // A user's language-specific settings override default language-specific settings.
1286 for (language_name, user_language_settings) in &user_settings.languages {
1287 merge_settings(
1288 languages
1289 .entry(language_name.clone())
1290 .or_insert_with(|| defaults.clone()),
1291 user_language_settings,
1292 );
1293 }
1294
1295 for (language, patterns) in &user_settings.file_types {
1296 let mut builder = GlobSetBuilder::new();
1297
1298 let default_value = default_value.file_types.get(&language.clone());
1299
1300 // Merge the default value with the user's value.
1301 if let Some(patterns) = default_value {
1302 for pattern in patterns {
1303 builder.add(Glob::new(pattern)?);
1304 }
1305 }
1306
1307 for pattern in patterns {
1308 builder.add(Glob::new(pattern)?);
1309 }
1310
1311 file_types.insert(language.clone(), builder.build()?);
1312 }
1313 }
1314
1315 Ok(Self {
1316 edit_predictions: EditPredictionSettings {
1317 provider: if let Some(provider) = edit_prediction_provider {
1318 provider
1319 } else {
1320 EditPredictionProvider::None
1321 },
1322 disabled_globs: completion_globs
1323 .iter()
1324 .filter_map(|g| {
1325 Some(DisabledGlob {
1326 matcher: globset::Glob::new(g).ok()?.compile_matcher(),
1327 is_absolute: Path::new(g).is_absolute(),
1328 })
1329 })
1330 .collect(),
1331 mode: edit_predictions_mode,
1332 copilot: copilot_settings,
1333 enabled_in_text_threads,
1334 },
1335 defaults,
1336 languages,
1337 file_types,
1338 })
1339 }
1340
1341 fn json_schema(
1342 generator: &mut schemars::r#gen::SchemaGenerator,
1343 params: &settings::SettingsJsonSchemaParams,
1344 _: &App,
1345 ) -> schemars::schema::RootSchema {
1346 let mut root_schema = generator.root_schema_for::<Self::FileContent>();
1347
1348 // Create a schema for a 'languages overrides' object, associating editor
1349 // settings with specific languages.
1350 assert!(
1351 root_schema
1352 .definitions
1353 .contains_key("LanguageSettingsContent")
1354 );
1355
1356 let languages_object_schema = SchemaObject {
1357 instance_type: Some(InstanceType::Object.into()),
1358 object: Some(Box::new(ObjectValidation {
1359 properties: params
1360 .language_names
1361 .iter()
1362 .map(|name| {
1363 (
1364 name.clone(),
1365 Schema::new_ref("#/definitions/LanguageSettingsContent".into()),
1366 )
1367 })
1368 .collect(),
1369 ..Default::default()
1370 })),
1371 ..Default::default()
1372 };
1373
1374 root_schema
1375 .definitions
1376 .extend([("Languages".into(), languages_object_schema.into())]);
1377
1378 add_references_to_properties(
1379 &mut root_schema,
1380 &[("languages", "#/definitions/Languages")],
1381 );
1382
1383 root_schema
1384 }
1385
1386 fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
1387 let d = &mut current.defaults;
1388 if let Some(size) = vscode
1389 .read_value("editor.tabSize")
1390 .and_then(|v| v.as_u64())
1391 .and_then(|n| NonZeroU32::new(n as u32))
1392 {
1393 d.tab_size = Some(size);
1394 }
1395 if let Some(v) = vscode.read_bool("editor.insertSpaces") {
1396 d.hard_tabs = Some(!v);
1397 }
1398
1399 vscode.enum_setting("editor.wordWrap", &mut d.soft_wrap, |s| match s {
1400 "on" => Some(SoftWrap::EditorWidth),
1401 "wordWrapColumn" => Some(SoftWrap::PreferLine),
1402 "bounded" => Some(SoftWrap::Bounded),
1403 "off" => Some(SoftWrap::None),
1404 _ => None,
1405 });
1406 vscode.u32_setting("editor.wordWrapColumn", &mut d.preferred_line_length);
1407
1408 if let Some(arr) = vscode
1409 .read_value("editor.rulers")
1410 .and_then(|v| v.as_array())
1411 .map(|v| v.iter().map(|n| n.as_u64().map(|n| n as usize)).collect())
1412 {
1413 d.wrap_guides = arr;
1414 }
1415 if let Some(b) = vscode.read_bool("editor.guides.indentation") {
1416 if let Some(guide_settings) = d.indent_guides.as_mut() {
1417 guide_settings.enabled = b;
1418 } else {
1419 d.indent_guides = Some(IndentGuideSettings {
1420 enabled: b,
1421 ..Default::default()
1422 });
1423 }
1424 }
1425
1426 if let Some(b) = vscode.read_bool("editor.guides.formatOnSave") {
1427 d.format_on_save = Some(if b {
1428 FormatOnSave::On
1429 } else {
1430 FormatOnSave::Off
1431 });
1432 }
1433 vscode.bool_setting(
1434 "editor.trimAutoWhitespace",
1435 &mut d.remove_trailing_whitespace_on_save,
1436 );
1437 vscode.bool_setting(
1438 "files.insertFinalNewline",
1439 &mut d.ensure_final_newline_on_save,
1440 );
1441 vscode.bool_setting("editor.inlineSuggest.enabled", &mut d.show_edit_predictions);
1442 vscode.enum_setting("editor.renderWhitespace", &mut d.show_whitespaces, |s| {
1443 Some(match s {
1444 "boundary" | "trailing" => ShowWhitespaceSetting::Boundary,
1445 "selection" => ShowWhitespaceSetting::Selection,
1446 "all" => ShowWhitespaceSetting::All,
1447 _ => ShowWhitespaceSetting::None,
1448 })
1449 });
1450 vscode.enum_setting(
1451 "editor.autoSurround",
1452 &mut d.use_auto_surround,
1453 |s| match s {
1454 "languageDefined" | "quotes" | "brackets" => Some(true),
1455 "never" => Some(false),
1456 _ => None,
1457 },
1458 );
1459 vscode.bool_setting("editor.formatOnType", &mut d.use_on_type_format);
1460 vscode.bool_setting("editor.linkedEditing", &mut d.linked_edits);
1461 vscode.bool_setting("editor.formatOnPaste", &mut d.auto_indent_on_paste);
1462 vscode.bool_setting(
1463 "editor.suggestOnTriggerCharacters",
1464 &mut d.show_completions_on_input,
1465 );
1466 if let Some(b) = vscode.read_bool("editor.suggest.showWords") {
1467 let mode = if b {
1468 WordsCompletionMode::Enabled
1469 } else {
1470 WordsCompletionMode::Disabled
1471 };
1472 if let Some(completion_settings) = d.completions.as_mut() {
1473 completion_settings.words = mode;
1474 } else {
1475 d.completions = Some(CompletionSettings {
1476 words: mode,
1477 lsp: true,
1478 lsp_fetch_timeout_ms: 0,
1479 lsp_insert_mode: LspInsertMode::ReplaceSuffix,
1480 });
1481 }
1482 }
1483 // TODO: pull ^ out into helper and reuse for per-language settings
1484
1485 // vscodes file association map is inverted from ours, so we flip the mapping before merging
1486 let mut associations: HashMap<Arc<str>, Vec<String>> = HashMap::default();
1487 if let Some(map) = vscode
1488 .read_value("files.associations")
1489 .and_then(|v| v.as_object())
1490 {
1491 for (k, v) in map {
1492 let Some(v) = v.as_str() else { continue };
1493 associations.entry(v.into()).or_default().push(k.clone());
1494 }
1495 }
1496
1497 // TODO: do we want to merge imported globs per filetype? for now we'll just replace
1498 current.file_types.extend(associations);
1499
1500 // cursor global ignore list applies to cursor-tab, so transfer it to edit_predictions.disabled_globs
1501 if let Some(disabled_globs) = vscode
1502 .read_value("cursor.general.globalCursorIgnoreList")
1503 .and_then(|v| v.as_array())
1504 {
1505 current
1506 .edit_predictions
1507 .get_or_insert_default()
1508 .disabled_globs
1509 .get_or_insert_default()
1510 .extend(
1511 disabled_globs
1512 .iter()
1513 .filter_map(|glob| glob.as_str())
1514 .map(|s| s.to_string()),
1515 );
1516 }
1517 }
1518}
1519
1520fn merge_settings(settings: &mut LanguageSettings, src: &LanguageSettingsContent) {
1521 fn merge<T>(target: &mut T, value: Option<T>) {
1522 if let Some(value) = value {
1523 *target = value;
1524 }
1525 }
1526
1527 merge(&mut settings.tab_size, src.tab_size);
1528 settings.tab_size = settings
1529 .tab_size
1530 .clamp(NonZeroU32::new(1).unwrap(), NonZeroU32::new(16).unwrap());
1531
1532 merge(&mut settings.hard_tabs, src.hard_tabs);
1533 merge(&mut settings.soft_wrap, src.soft_wrap);
1534 merge(&mut settings.use_autoclose, src.use_autoclose);
1535 merge(&mut settings.use_auto_surround, src.use_auto_surround);
1536 merge(&mut settings.use_on_type_format, src.use_on_type_format);
1537 merge(&mut settings.auto_indent_on_paste, src.auto_indent_on_paste);
1538 merge(
1539 &mut settings.always_treat_brackets_as_autoclosed,
1540 src.always_treat_brackets_as_autoclosed,
1541 );
1542 merge(&mut settings.show_wrap_guides, src.show_wrap_guides);
1543 merge(&mut settings.wrap_guides, src.wrap_guides.clone());
1544 merge(&mut settings.indent_guides, src.indent_guides);
1545 merge(
1546 &mut settings.code_actions_on_format,
1547 src.code_actions_on_format.clone(),
1548 );
1549 merge(&mut settings.linked_edits, src.linked_edits);
1550 merge(&mut settings.tasks, src.tasks.clone());
1551
1552 merge(
1553 &mut settings.preferred_line_length,
1554 src.preferred_line_length,
1555 );
1556 merge(&mut settings.formatter, src.formatter.clone());
1557 merge(&mut settings.prettier, src.prettier.clone());
1558 merge(
1559 &mut settings.jsx_tag_auto_close,
1560 src.jsx_tag_auto_close.clone(),
1561 );
1562 merge(&mut settings.format_on_save, src.format_on_save.clone());
1563 merge(
1564 &mut settings.remove_trailing_whitespace_on_save,
1565 src.remove_trailing_whitespace_on_save,
1566 );
1567 merge(
1568 &mut settings.ensure_final_newline_on_save,
1569 src.ensure_final_newline_on_save,
1570 );
1571 merge(
1572 &mut settings.enable_language_server,
1573 src.enable_language_server,
1574 );
1575 merge(&mut settings.language_servers, src.language_servers.clone());
1576 merge(&mut settings.allow_rewrap, src.allow_rewrap);
1577 merge(
1578 &mut settings.show_edit_predictions,
1579 src.show_edit_predictions,
1580 );
1581 merge(
1582 &mut settings.edit_predictions_disabled_in,
1583 src.edit_predictions_disabled_in.clone(),
1584 );
1585 merge(&mut settings.show_whitespaces, src.show_whitespaces);
1586 merge(
1587 &mut settings.extend_comment_on_newline,
1588 src.extend_comment_on_newline,
1589 );
1590 merge(&mut settings.inlay_hints, src.inlay_hints);
1591 merge(
1592 &mut settings.show_completions_on_input,
1593 src.show_completions_on_input,
1594 );
1595 merge(
1596 &mut settings.show_completion_documentation,
1597 src.show_completion_documentation,
1598 );
1599 merge(&mut settings.completions, src.completions);
1600}
1601
1602/// Allows to enable/disable formatting with Prettier
1603/// and configure default Prettier, used when no project-level Prettier installation is found.
1604/// Prettier formatting is disabled by default.
1605#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1606pub struct PrettierSettings {
1607 /// Enables or disables formatting with Prettier for a given language.
1608 #[serde(default)]
1609 pub allowed: bool,
1610
1611 /// Forces Prettier integration to use a specific parser name when formatting files with the language.
1612 #[serde(default)]
1613 pub parser: Option<String>,
1614
1615 /// Forces Prettier integration to use specific plugins when formatting files with the language.
1616 /// The default Prettier will be installed with these plugins.
1617 #[serde(default)]
1618 pub plugins: HashSet<String>,
1619
1620 /// Default Prettier options, in the format as in package.json section for Prettier.
1621 /// If project installs Prettier via its package.json, these options will be ignored.
1622 #[serde(flatten)]
1623 pub options: HashMap<String, serde_json::Value>,
1624}
1625
1626#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1627pub struct JsxTagAutoCloseSettings {
1628 /// Enables or disables auto-closing of JSX tags.
1629 #[serde(default)]
1630 pub enabled: bool,
1631}
1632
1633#[cfg(test)]
1634mod tests {
1635 use gpui::TestAppContext;
1636
1637 use super::*;
1638
1639 #[test]
1640 fn test_formatter_deserialization() {
1641 let raw_auto = "{\"formatter\": \"auto\"}";
1642 let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
1643 assert_eq!(settings.formatter, Some(SelectedFormatter::Auto));
1644 let raw = "{\"formatter\": \"language_server\"}";
1645 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1646 assert_eq!(
1647 settings.formatter,
1648 Some(SelectedFormatter::List(FormatterList(
1649 Formatter::LanguageServer { name: None }.into()
1650 )))
1651 );
1652 let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
1653 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1654 assert_eq!(
1655 settings.formatter,
1656 Some(SelectedFormatter::List(FormatterList(
1657 vec![Formatter::LanguageServer { name: None }].into()
1658 )))
1659 );
1660 let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"prettier\"]}";
1661 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1662 assert_eq!(
1663 settings.formatter,
1664 Some(SelectedFormatter::List(FormatterList(
1665 vec![
1666 Formatter::LanguageServer { name: None },
1667 Formatter::Prettier
1668 ]
1669 .into()
1670 )))
1671 );
1672 }
1673
1674 #[test]
1675 fn test_formatter_deserialization_invalid() {
1676 let raw_auto = "{\"formatter\": {}}";
1677 let result: Result<LanguageSettingsContent, _> = serde_json::from_str(raw_auto);
1678 assert!(result.is_err());
1679 }
1680
1681 #[gpui::test]
1682 fn test_edit_predictions_enabled_for_file(cx: &mut TestAppContext) {
1683 use crate::TestFile;
1684 use std::path::PathBuf;
1685
1686 let cx = cx.app.borrow_mut();
1687
1688 let build_settings = |globs: &[&str]| -> EditPredictionSettings {
1689 EditPredictionSettings {
1690 disabled_globs: globs
1691 .iter()
1692 .map(|glob_str| {
1693 #[cfg(windows)]
1694 let glob_str = {
1695 let mut g = String::new();
1696
1697 if glob_str.starts_with('/') {
1698 g.push_str("C:");
1699 }
1700
1701 g.push_str(&glob_str.replace('/', "\\"));
1702 g
1703 };
1704 #[cfg(windows)]
1705 let glob_str = glob_str.as_str();
1706
1707 DisabledGlob {
1708 matcher: globset::Glob::new(glob_str).unwrap().compile_matcher(),
1709 is_absolute: Path::new(glob_str).is_absolute(),
1710 }
1711 })
1712 .collect(),
1713 ..Default::default()
1714 }
1715 };
1716
1717 const WORKTREE_NAME: &str = "project";
1718 let make_test_file = |segments: &[&str]| -> Arc<dyn File> {
1719 let mut path_buf = PathBuf::new();
1720 path_buf.extend(segments);
1721
1722 Arc::new(TestFile {
1723 path: path_buf.as_path().into(),
1724 root_name: WORKTREE_NAME.to_string(),
1725 local_root: Some(PathBuf::from(if cfg!(windows) {
1726 "C:\\absolute\\"
1727 } else {
1728 "/absolute/"
1729 })),
1730 })
1731 };
1732
1733 let test_file = make_test_file(&["src", "test", "file.rs"]);
1734
1735 // Test relative globs
1736 let settings = build_settings(&["*.rs"]);
1737 assert!(!settings.enabled_for_file(&test_file, &cx));
1738 let settings = build_settings(&["*.txt"]);
1739 assert!(settings.enabled_for_file(&test_file, &cx));
1740
1741 // Test absolute globs
1742 let settings = build_settings(&["/absolute/**/*.rs"]);
1743 assert!(!settings.enabled_for_file(&test_file, &cx));
1744 let settings = build_settings(&["/other/**/*.rs"]);
1745 assert!(settings.enabled_for_file(&test_file, &cx));
1746
1747 // Test exact path match relative
1748 let settings = build_settings(&["src/test/file.rs"]);
1749 assert!(!settings.enabled_for_file(&test_file, &cx));
1750 let settings = build_settings(&["src/test/otherfile.rs"]);
1751 assert!(settings.enabled_for_file(&test_file, &cx));
1752
1753 // Test exact path match absolute
1754 let settings = build_settings(&[&format!("/absolute/{}/src/test/file.rs", WORKTREE_NAME)]);
1755 assert!(!settings.enabled_for_file(&test_file, &cx));
1756 let settings = build_settings(&["/other/test/otherfile.rs"]);
1757 assert!(settings.enabled_for_file(&test_file, &cx));
1758
1759 // Test * glob
1760 let settings = build_settings(&["*"]);
1761 assert!(!settings.enabled_for_file(&test_file, &cx));
1762 let settings = build_settings(&["*.txt"]);
1763 assert!(settings.enabled_for_file(&test_file, &cx));
1764
1765 // Test **/* glob
1766 let settings = build_settings(&["**/*"]);
1767 assert!(!settings.enabled_for_file(&test_file, &cx));
1768 let settings = build_settings(&["other/**/*"]);
1769 assert!(settings.enabled_for_file(&test_file, &cx));
1770
1771 // Test directory/** glob
1772 let settings = build_settings(&["src/**"]);
1773 assert!(!settings.enabled_for_file(&test_file, &cx));
1774
1775 let test_file_root: Arc<dyn File> = Arc::new(TestFile {
1776 path: PathBuf::from("file.rs").as_path().into(),
1777 root_name: WORKTREE_NAME.to_string(),
1778 local_root: Some(PathBuf::from("/absolute/")),
1779 });
1780 assert!(settings.enabled_for_file(&test_file_root, &cx));
1781
1782 let settings = build_settings(&["other/**"]);
1783 assert!(settings.enabled_for_file(&test_file, &cx));
1784
1785 // Test **/directory/* glob
1786 let settings = build_settings(&["**/test/*"]);
1787 assert!(!settings.enabled_for_file(&test_file, &cx));
1788 let settings = build_settings(&["**/other/*"]);
1789 assert!(settings.enabled_for_file(&test_file, &cx));
1790
1791 // Test multiple globs
1792 let settings = build_settings(&["*.rs", "*.txt", "src/**"]);
1793 assert!(!settings.enabled_for_file(&test_file, &cx));
1794 let settings = build_settings(&["*.txt", "*.md", "other/**"]);
1795 assert!(settings.enabled_for_file(&test_file, &cx));
1796
1797 // Test dot files
1798 let dot_file = make_test_file(&[".config", "settings.json"]);
1799 let settings = build_settings(&[".*/**"]);
1800 assert!(!settings.enabled_for_file(&dot_file, &cx));
1801
1802 let dot_env_file = make_test_file(&[".env"]);
1803 let settings = build_settings(&[".env"]);
1804 assert!(!settings.enabled_for_file(&dot_env_file, &cx));
1805 }
1806
1807 #[test]
1808 pub fn test_resolve_language_servers() {
1809 fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
1810 names
1811 .iter()
1812 .copied()
1813 .map(|name| LanguageServerName(name.to_string().into()))
1814 .collect::<Vec<_>>()
1815 }
1816
1817 let available_language_servers = language_server_names(&[
1818 "typescript-language-server",
1819 "biome",
1820 "deno",
1821 "eslint",
1822 "tailwind",
1823 ]);
1824
1825 // A value of just `["..."]` is the same as taking all of the available language servers.
1826 assert_eq!(
1827 LanguageSettings::resolve_language_servers(
1828 &[LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()],
1829 &available_language_servers,
1830 ),
1831 available_language_servers
1832 );
1833
1834 // Referencing one of the available language servers will change its order.
1835 assert_eq!(
1836 LanguageSettings::resolve_language_servers(
1837 &[
1838 "biome".into(),
1839 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into(),
1840 "deno".into()
1841 ],
1842 &available_language_servers
1843 ),
1844 language_server_names(&[
1845 "biome",
1846 "typescript-language-server",
1847 "eslint",
1848 "tailwind",
1849 "deno",
1850 ])
1851 );
1852
1853 // Negating an available language server removes it from the list.
1854 assert_eq!(
1855 LanguageSettings::resolve_language_servers(
1856 &[
1857 "deno".into(),
1858 "!typescript-language-server".into(),
1859 "!biome".into(),
1860 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1861 ],
1862 &available_language_servers
1863 ),
1864 language_server_names(&["deno", "eslint", "tailwind"])
1865 );
1866
1867 // Adding a language server not in the list of available language servers adds it to the list.
1868 assert_eq!(
1869 LanguageSettings::resolve_language_servers(
1870 &[
1871 "my-cool-language-server".into(),
1872 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1873 ],
1874 &available_language_servers
1875 ),
1876 language_server_names(&[
1877 "my-cool-language-server",
1878 "typescript-language-server",
1879 "biome",
1880 "deno",
1881 "eslint",
1882 "tailwind",
1883 ])
1884 );
1885 }
1886}