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