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