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