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