1//! Provides `language`-related settings.
2
3use crate::{File, Language, LanguageName, LanguageServerName};
4use anyhow::Result;
5use collections::{HashMap, HashSet};
6use core::slice;
7use ec4rs::{
8 property::{FinalNewline, IndentSize, IndentStyle, TabWidth, TrimTrailingWs},
9 Properties as EditorconfigProperties,
10};
11use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
12use gpui::App;
13use itertools::{Either, Itertools};
14use schemars::{
15 schema::{InstanceType, ObjectValidation, Schema, SchemaObject, SingleOrVec},
16 JsonSchema,
17};
18use serde::{
19 de::{self, IntoDeserializer, MapAccess, SeqAccess, Visitor},
20 Deserialize, Deserializer, Serialize,
21};
22use serde_json::Value;
23use settings::{
24 add_references_to_properties, Settings, SettingsLocation, SettingsSources, SettingsStore,
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 inline completion settings.
63 pub inline_completions: InlineCompletionSettings,
64 defaults: LanguageSettings,
65 languages: HashMap<LanguageName, LanguageSettings>,
66 pub(crate) file_types: HashMap<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 use language servers to provide code intelligence.
104 pub enable_language_server: bool,
105 /// The list of language servers to use (or disable) for this language.
106 ///
107 /// This array should consist of language server IDs, as well as the following
108 /// special tokens:
109 /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
110 /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
111 pub language_servers: Vec<String>,
112 /// Controls whether inline completions are shown immediately (true)
113 /// or manually by triggering `editor::ShowInlineCompletion` (false).
114 pub show_inline_completions: bool,
115 /// Controls whether inline completions are shown in the given language
116 /// scopes.
117 pub inline_completions_disabled_in: Vec<String>,
118 /// Whether to show tabs and spaces in the editor.
119 pub show_whitespaces: ShowWhitespaceSetting,
120 /// Whether to start a new line with a comment when a previous line is a comment as well.
121 pub extend_comment_on_newline: bool,
122 /// Inlay hint related settings.
123 pub inlay_hints: InlayHintSettings,
124 /// Whether to automatically close brackets.
125 pub use_autoclose: bool,
126 /// Whether to automatically surround text with brackets.
127 pub use_auto_surround: bool,
128 /// Whether to use additional LSP queries to format (and amend) the code after
129 /// every "trigger" symbol input, defined by LSP server capabilities.
130 pub use_on_type_format: bool,
131 /// Whether indentation of pasted content should be adjusted based on the context.
132 pub auto_indent_on_paste: bool,
133 // Controls how the editor handles the autoclosed characters.
134 pub always_treat_brackets_as_autoclosed: bool,
135 /// Which code actions to run on save
136 pub code_actions_on_format: HashMap<String, bool>,
137 /// Whether to perform linked edits
138 pub linked_edits: bool,
139 /// Task configuration for this language.
140 pub tasks: LanguageTaskConfig,
141 /// Whether to pop the completions menu while typing in an editor without
142 /// explicitly requesting it.
143 pub show_completions_on_input: bool,
144 /// Whether to display inline and alongside documentation for items in the
145 /// completions menu.
146 pub show_completion_documentation: bool,
147}
148
149impl LanguageSettings {
150 /// A token representing the rest of the available language servers.
151 const REST_OF_LANGUAGE_SERVERS: &'static str = "...";
152
153 /// Returns the customized list of language servers from the list of
154 /// available language servers.
155 pub fn customized_language_servers(
156 &self,
157 available_language_servers: &[LanguageServerName],
158 ) -> Vec<LanguageServerName> {
159 Self::resolve_language_servers(&self.language_servers, available_language_servers)
160 }
161
162 pub(crate) fn resolve_language_servers(
163 configured_language_servers: &[String],
164 available_language_servers: &[LanguageServerName],
165 ) -> Vec<LanguageServerName> {
166 let (disabled_language_servers, enabled_language_servers): (
167 Vec<LanguageServerName>,
168 Vec<LanguageServerName>,
169 ) = configured_language_servers.iter().partition_map(
170 |language_server| match language_server.strip_prefix('!') {
171 Some(disabled) => Either::Left(LanguageServerName(disabled.to_string().into())),
172 None => Either::Right(LanguageServerName(language_server.clone().into())),
173 },
174 );
175
176 let rest = available_language_servers
177 .iter()
178 .filter(|&available_language_server| {
179 !disabled_language_servers.contains(&available_language_server)
180 && !enabled_language_servers.contains(&available_language_server)
181 })
182 .cloned()
183 .collect::<Vec<_>>();
184
185 enabled_language_servers
186 .into_iter()
187 .flat_map(|language_server| {
188 if language_server.0.as_ref() == Self::REST_OF_LANGUAGE_SERVERS {
189 rest.clone()
190 } else {
191 vec![language_server.clone()]
192 }
193 })
194 .collect::<Vec<_>>()
195 }
196}
197
198/// The provider that supplies inline completions.
199#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
200#[serde(rename_all = "snake_case")]
201pub enum InlineCompletionProvider {
202 None,
203 #[default]
204 Copilot,
205 Supermaven,
206 Zed,
207}
208
209/// The settings for inline completions, such as [GitHub Copilot](https://github.com/features/copilot)
210/// or [Supermaven](https://supermaven.com).
211#[derive(Clone, Debug, Default)]
212pub struct InlineCompletionSettings {
213 /// The provider that supplies inline completions.
214 pub provider: InlineCompletionProvider,
215 /// A list of globs representing files that inline completions should be disabled for.
216 pub disabled_globs: Vec<GlobMatcher>,
217}
218
219/// The settings for all languages.
220#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
221pub struct AllLanguageSettingsContent {
222 /// The settings for enabling/disabling features.
223 #[serde(default)]
224 pub features: Option<FeaturesContent>,
225 /// The inline completion settings.
226 #[serde(default)]
227 pub inline_completions: Option<InlineCompletionSettingsContent>,
228 /// The default language settings.
229 #[serde(flatten)]
230 pub defaults: LanguageSettingsContent,
231 /// The settings for individual languages.
232 #[serde(default)]
233 pub languages: HashMap<LanguageName, LanguageSettingsContent>,
234 /// Settings for associating file extensions and filenames
235 /// with languages.
236 #[serde(default)]
237 pub file_types: HashMap<Arc<str>, Vec<String>>,
238}
239
240/// The settings for a particular language.
241#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
242pub struct LanguageSettingsContent {
243 /// How many columns a tab should occupy.
244 ///
245 /// Default: 4
246 #[serde(default)]
247 pub tab_size: Option<NonZeroU32>,
248 /// Whether to indent lines using tab characters, as opposed to multiple
249 /// spaces.
250 ///
251 /// Default: false
252 #[serde(default)]
253 pub hard_tabs: Option<bool>,
254 /// How to soft-wrap long lines of text.
255 ///
256 /// Default: none
257 #[serde(default)]
258 pub soft_wrap: Option<SoftWrap>,
259 /// The column at which to soft-wrap lines, for buffers where soft-wrap
260 /// is enabled.
261 ///
262 /// Default: 80
263 #[serde(default)]
264 pub preferred_line_length: Option<u32>,
265 /// Whether to show wrap guides in the editor. Setting this to true will
266 /// show a guide at the 'preferred_line_length' value if softwrap is set to
267 /// 'preferred_line_length', and will show any additional guides as specified
268 /// by the 'wrap_guides' setting.
269 ///
270 /// Default: true
271 #[serde(default)]
272 pub show_wrap_guides: Option<bool>,
273 /// Character counts at which to show wrap guides in the editor.
274 ///
275 /// Default: []
276 #[serde(default)]
277 pub wrap_guides: Option<Vec<usize>>,
278 /// Indent guide related settings.
279 #[serde(default)]
280 pub indent_guides: Option<IndentGuideSettings>,
281 /// Whether or not to perform a buffer format before saving.
282 ///
283 /// Default: on
284 #[serde(default)]
285 pub format_on_save: Option<FormatOnSave>,
286 /// Whether or not to remove any trailing whitespace from lines of a buffer
287 /// before saving it.
288 ///
289 /// Default: true
290 #[serde(default)]
291 pub remove_trailing_whitespace_on_save: Option<bool>,
292 /// Whether or not to ensure there's a single newline at the end of a buffer
293 /// when saving it.
294 ///
295 /// Default: true
296 #[serde(default)]
297 pub ensure_final_newline_on_save: Option<bool>,
298 /// How to perform a buffer format.
299 ///
300 /// Default: auto
301 #[serde(default)]
302 pub formatter: Option<SelectedFormatter>,
303 /// Zed's Prettier integration settings.
304 /// Allows to enable/disable formatting with Prettier
305 /// and configure default Prettier, used when no project-level Prettier installation is found.
306 ///
307 /// Default: off
308 #[serde(default)]
309 pub prettier: Option<PrettierSettings>,
310 /// Whether to use language servers to provide code intelligence.
311 ///
312 /// Default: true
313 #[serde(default)]
314 pub enable_language_server: Option<bool>,
315 /// The list of language servers to use (or disable) for this language.
316 ///
317 /// This array should consist of language server IDs, as well as the following
318 /// special tokens:
319 /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
320 /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
321 ///
322 /// Default: ["..."]
323 #[serde(default)]
324 pub language_servers: Option<Vec<String>>,
325 /// Controls whether inline completions are shown immediately (true)
326 /// or manually by triggering `editor::ShowInlineCompletion` (false).
327 ///
328 /// Default: true
329 #[serde(default)]
330 pub show_inline_completions: Option<bool>,
331 /// Controls whether inline completions are shown in the given language
332 /// scopes.
333 ///
334 /// Example: ["string", "comment"]
335 ///
336 /// Default: []
337 #[serde(default)]
338 pub inline_completions_disabled_in: Option<Vec<String>>,
339 /// Whether to show tabs and spaces in the editor.
340 #[serde(default)]
341 pub show_whitespaces: Option<ShowWhitespaceSetting>,
342 /// Whether to start a new line with a comment when a previous line is a comment as well.
343 ///
344 /// Default: true
345 #[serde(default)]
346 pub extend_comment_on_newline: Option<bool>,
347 /// Inlay hint related settings.
348 #[serde(default)]
349 pub inlay_hints: Option<InlayHintSettings>,
350 /// Whether to automatically type closing characters for you. For example,
351 /// when you type (, Zed will automatically add a closing ) at the correct position.
352 ///
353 /// Default: true
354 pub use_autoclose: Option<bool>,
355 /// Whether to automatically surround text with characters for you. For example,
356 /// when you select text and type (, Zed will automatically surround text with ().
357 ///
358 /// Default: true
359 pub use_auto_surround: Option<bool>,
360 /// Controls how the editor handles the autoclosed characters.
361 /// When set to `false`(default), skipping over and auto-removing of the closing characters
362 /// happen only for auto-inserted characters.
363 /// Otherwise(when `true`), the closing characters are always skipped over and auto-removed
364 /// no matter how they were inserted.
365 ///
366 /// Default: false
367 pub always_treat_brackets_as_autoclosed: Option<bool>,
368 /// Whether to use additional LSP queries to format (and amend) the code after
369 /// every "trigger" symbol input, defined by LSP server capabilities.
370 ///
371 /// Default: true
372 pub use_on_type_format: Option<bool>,
373 /// Which code actions to run on save after the formatter.
374 /// These are not run if formatting is off.
375 ///
376 /// Default: {} (or {"source.organizeImports": true} for Go).
377 pub code_actions_on_format: Option<HashMap<String, bool>>,
378 /// Whether to perform linked edits of associated ranges, if the language server supports it.
379 /// For example, when editing opening <html> tag, the contents of the closing </html> tag will be edited as well.
380 ///
381 /// Default: true
382 pub linked_edits: Option<bool>,
383 /// Whether indentation of pasted content should be adjusted based on the context.
384 ///
385 /// Default: true
386 pub auto_indent_on_paste: Option<bool>,
387 /// Task configuration for this language.
388 ///
389 /// Default: {}
390 pub tasks: Option<LanguageTaskConfig>,
391 /// Whether to pop the completions menu while typing in an editor without
392 /// explicitly requesting it.
393 ///
394 /// Default: true
395 pub show_completions_on_input: Option<bool>,
396 /// Whether to display inline and alongside documentation for items in the
397 /// completions menu.
398 ///
399 /// Default: true
400 pub show_completion_documentation: Option<bool>,
401}
402
403/// The contents of the inline completion settings.
404#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)]
405pub struct InlineCompletionSettingsContent {
406 /// A list of globs representing files that inline completions should be disabled for.
407 #[serde(default)]
408 pub disabled_globs: Option<Vec<String>>,
409}
410
411/// The settings for enabling/disabling features.
412#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
413#[serde(rename_all = "snake_case")]
414pub struct FeaturesContent {
415 /// Whether the GitHub Copilot feature is enabled.
416 pub copilot: Option<bool>,
417 /// Determines which inline completion provider to use.
418 pub inline_completion_provider: Option<InlineCompletionProvider>,
419}
420
421/// Controls the soft-wrapping behavior in the editor.
422#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
423#[serde(rename_all = "snake_case")]
424pub enum SoftWrap {
425 /// Prefer a single line generally, unless an overly long line is encountered.
426 None,
427 /// Deprecated: use None instead. Left to avoid breaking existing users' configs.
428 /// Prefer a single line generally, unless an overly long line is encountered.
429 PreferLine,
430 /// Soft wrap lines that exceed the editor width.
431 EditorWidth,
432 /// Soft wrap lines at the preferred line length.
433 PreferredLineLength,
434 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
435 Bounded,
436}
437
438/// Controls the behavior of formatting files when they are saved.
439#[derive(Debug, Clone, PartialEq, Eq)]
440pub enum FormatOnSave {
441 /// Files should be formatted on save.
442 On,
443 /// Files should not be formatted on save.
444 Off,
445 List(FormatterList),
446}
447
448impl JsonSchema for FormatOnSave {
449 fn schema_name() -> String {
450 "OnSaveFormatter".into()
451 }
452
453 fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> Schema {
454 let mut schema = SchemaObject::default();
455 let formatter_schema = Formatter::json_schema(generator);
456 schema.instance_type = Some(
457 vec![
458 InstanceType::Object,
459 InstanceType::String,
460 InstanceType::Array,
461 ]
462 .into(),
463 );
464
465 let valid_raw_values = SchemaObject {
466 enum_values: Some(vec![
467 Value::String("on".into()),
468 Value::String("off".into()),
469 Value::String("prettier".into()),
470 Value::String("language_server".into()),
471 ]),
472 ..Default::default()
473 };
474 let mut nested_values = SchemaObject::default();
475
476 nested_values.array().items = Some(formatter_schema.clone().into());
477
478 schema.subschemas().any_of = Some(vec![
479 nested_values.into(),
480 valid_raw_values.into(),
481 formatter_schema,
482 ]);
483 schema.into()
484 }
485}
486
487impl Serialize for FormatOnSave {
488 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
489 where
490 S: serde::Serializer,
491 {
492 match self {
493 Self::On => serializer.serialize_str("on"),
494 Self::Off => serializer.serialize_str("off"),
495 Self::List(list) => list.serialize(serializer),
496 }
497 }
498}
499
500impl<'de> Deserialize<'de> for FormatOnSave {
501 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
502 where
503 D: Deserializer<'de>,
504 {
505 struct FormatDeserializer;
506
507 impl<'d> Visitor<'d> for FormatDeserializer {
508 type Value = FormatOnSave;
509
510 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
511 formatter.write_str("a valid on-save formatter kind")
512 }
513 fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
514 where
515 E: serde::de::Error,
516 {
517 if v == "on" {
518 Ok(Self::Value::On)
519 } else if v == "off" {
520 Ok(Self::Value::Off)
521 } else if v == "language_server" {
522 Ok(Self::Value::List(FormatterList(
523 Formatter::LanguageServer { name: None }.into(),
524 )))
525 } else {
526 let ret: Result<FormatterList, _> =
527 Deserialize::deserialize(v.into_deserializer());
528 ret.map(Self::Value::List)
529 }
530 }
531 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
532 where
533 A: MapAccess<'d>,
534 {
535 let ret: Result<FormatterList, _> =
536 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
537 ret.map(Self::Value::List)
538 }
539 fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
540 where
541 A: SeqAccess<'d>,
542 {
543 let ret: Result<FormatterList, _> =
544 Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
545 ret.map(Self::Value::List)
546 }
547 }
548 deserializer.deserialize_any(FormatDeserializer)
549 }
550}
551
552/// Controls how whitespace should be displayedin the editor.
553#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
554#[serde(rename_all = "snake_case")]
555pub enum ShowWhitespaceSetting {
556 /// Draw whitespace only for the selected text.
557 Selection,
558 /// Do not draw any tabs or spaces.
559 None,
560 /// Draw all invisible symbols.
561 All,
562 /// Draw whitespaces at boundaries only.
563 ///
564 /// For a whitespace to be on a boundary, any of the following conditions need to be met:
565 /// - It is a tab
566 /// - It is adjacent to an edge (start or end)
567 /// - It is adjacent to a whitespace (left or right)
568 Boundary,
569}
570
571/// Controls which formatter should be used when formatting code.
572#[derive(Clone, Debug, Default, PartialEq, Eq)]
573pub enum SelectedFormatter {
574 /// Format files using Zed's Prettier integration (if applicable),
575 /// or falling back to formatting via language server.
576 #[default]
577 Auto,
578 List(FormatterList),
579}
580
581impl JsonSchema for SelectedFormatter {
582 fn schema_name() -> String {
583 "Formatter".into()
584 }
585
586 fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> Schema {
587 let mut schema = SchemaObject::default();
588 let formatter_schema = Formatter::json_schema(generator);
589 schema.instance_type = Some(
590 vec![
591 InstanceType::Object,
592 InstanceType::String,
593 InstanceType::Array,
594 ]
595 .into(),
596 );
597
598 let valid_raw_values = SchemaObject {
599 enum_values: Some(vec![
600 Value::String("auto".into()),
601 Value::String("prettier".into()),
602 Value::String("language_server".into()),
603 ]),
604 ..Default::default()
605 };
606
607 let mut nested_values = SchemaObject::default();
608
609 nested_values.array().items = Some(formatter_schema.clone().into());
610
611 schema.subschemas().any_of = Some(vec![
612 nested_values.into(),
613 valid_raw_values.into(),
614 formatter_schema,
615 ]);
616 schema.into()
617 }
618}
619
620impl Serialize for SelectedFormatter {
621 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
622 where
623 S: serde::Serializer,
624 {
625 match self {
626 SelectedFormatter::Auto => serializer.serialize_str("auto"),
627 SelectedFormatter::List(list) => list.serialize(serializer),
628 }
629 }
630}
631impl<'de> Deserialize<'de> for SelectedFormatter {
632 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
633 where
634 D: Deserializer<'de>,
635 {
636 struct FormatDeserializer;
637
638 impl<'d> Visitor<'d> for FormatDeserializer {
639 type Value = SelectedFormatter;
640
641 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
642 formatter.write_str("a valid formatter kind")
643 }
644 fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
645 where
646 E: serde::de::Error,
647 {
648 if v == "auto" {
649 Ok(Self::Value::Auto)
650 } else if v == "language_server" {
651 Ok(Self::Value::List(FormatterList(
652 Formatter::LanguageServer { name: None }.into(),
653 )))
654 } else {
655 let ret: Result<FormatterList, _> =
656 Deserialize::deserialize(v.into_deserializer());
657 ret.map(SelectedFormatter::List)
658 }
659 }
660 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
661 where
662 A: MapAccess<'d>,
663 {
664 let ret: Result<FormatterList, _> =
665 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
666 ret.map(SelectedFormatter::List)
667 }
668 fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
669 where
670 A: SeqAccess<'d>,
671 {
672 let ret: Result<FormatterList, _> =
673 Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
674 ret.map(SelectedFormatter::List)
675 }
676 }
677 deserializer.deserialize_any(FormatDeserializer)
678 }
679}
680/// Controls which formatter should be used when formatting code.
681#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
682#[serde(rename_all = "snake_case", transparent)]
683pub struct FormatterList(pub SingleOrVec<Formatter>);
684
685impl AsRef<[Formatter]> for FormatterList {
686 fn as_ref(&self) -> &[Formatter] {
687 match &self.0 {
688 SingleOrVec::Single(single) => slice::from_ref(single),
689 SingleOrVec::Vec(v) => v,
690 }
691 }
692}
693
694/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
695#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
696#[serde(rename_all = "snake_case")]
697pub enum Formatter {
698 /// Format code using the current language server.
699 LanguageServer { name: Option<String> },
700 /// Format code using Zed's Prettier integration.
701 Prettier,
702 /// Format code using an external command.
703 External {
704 /// The external program to run.
705 command: Arc<str>,
706 /// The arguments to pass to the program.
707 arguments: Option<Arc<[String]>>,
708 },
709 /// Files should be formatted using code actions executed by language servers.
710 CodeActions(HashMap<String, bool>),
711}
712
713/// The settings for indent guides.
714#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
715pub struct IndentGuideSettings {
716 /// Whether to display indent guides in the editor.
717 ///
718 /// Default: true
719 #[serde(default = "default_true")]
720 pub enabled: bool,
721 /// The width of the indent guides in pixels, between 1 and 10.
722 ///
723 /// Default: 1
724 #[serde(default = "line_width")]
725 pub line_width: u32,
726 /// The width of the active indent guide in pixels, between 1 and 10.
727 ///
728 /// Default: 1
729 #[serde(default = "active_line_width")]
730 pub active_line_width: u32,
731 /// Determines how indent guides are colored.
732 ///
733 /// Default: Fixed
734 #[serde(default)]
735 pub coloring: IndentGuideColoring,
736 /// Determines how indent guide backgrounds are colored.
737 ///
738 /// Default: Disabled
739 #[serde(default)]
740 pub background_coloring: IndentGuideBackgroundColoring,
741}
742
743fn line_width() -> u32 {
744 1
745}
746
747fn active_line_width() -> u32 {
748 line_width()
749}
750
751/// Determines how indent guides are colored.
752#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
753#[serde(rename_all = "snake_case")]
754pub enum IndentGuideColoring {
755 /// Do not render any lines for indent guides.
756 Disabled,
757 /// Use the same color for all indentation levels.
758 #[default]
759 Fixed,
760 /// Use a different color for each indentation level.
761 IndentAware,
762}
763
764/// Determines how indent guide backgrounds are colored.
765#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
766#[serde(rename_all = "snake_case")]
767pub enum IndentGuideBackgroundColoring {
768 /// Do not render any background for indent guides.
769 #[default]
770 Disabled,
771 /// Use a different color for each indentation level.
772 IndentAware,
773}
774
775/// The settings for inlay hints.
776#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
777pub struct InlayHintSettings {
778 /// Global switch to toggle hints on and off.
779 ///
780 /// Default: false
781 #[serde(default)]
782 pub enabled: bool,
783 /// Whether type hints should be shown.
784 ///
785 /// Default: true
786 #[serde(default = "default_true")]
787 pub show_type_hints: bool,
788 /// Whether parameter hints should be shown.
789 ///
790 /// Default: true
791 #[serde(default = "default_true")]
792 pub show_parameter_hints: bool,
793 /// Whether other hints should be shown.
794 ///
795 /// Default: true
796 #[serde(default = "default_true")]
797 pub show_other_hints: bool,
798 /// Whether to show a background for inlay hints.
799 ///
800 /// If set to `true`, the background will use the `hint.background` color
801 /// from the current theme.
802 ///
803 /// Default: false
804 #[serde(default)]
805 pub show_background: bool,
806 /// Whether or not to debounce inlay hints updates after buffer edits.
807 ///
808 /// Set to 0 to disable debouncing.
809 ///
810 /// Default: 700
811 #[serde(default = "edit_debounce_ms")]
812 pub edit_debounce_ms: u64,
813 /// Whether or not to debounce inlay hints updates after buffer scrolls.
814 ///
815 /// Set to 0 to disable debouncing.
816 ///
817 /// Default: 50
818 #[serde(default = "scroll_debounce_ms")]
819 pub scroll_debounce_ms: u64,
820}
821
822fn edit_debounce_ms() -> u64 {
823 700
824}
825
826fn scroll_debounce_ms() -> u64 {
827 50
828}
829
830/// The task settings for a particular language.
831#[derive(Debug, Clone, Deserialize, PartialEq, Serialize, JsonSchema)]
832pub struct LanguageTaskConfig {
833 /// Extra task variables to set for a particular language.
834 pub variables: HashMap<String, String>,
835}
836
837impl InlayHintSettings {
838 /// Returns the kinds of inlay hints that are enabled based on the settings.
839 pub fn enabled_inlay_hint_kinds(&self) -> HashSet<Option<InlayHintKind>> {
840 let mut kinds = HashSet::default();
841 if self.show_type_hints {
842 kinds.insert(Some(InlayHintKind::Type));
843 }
844 if self.show_parameter_hints {
845 kinds.insert(Some(InlayHintKind::Parameter));
846 }
847 if self.show_other_hints {
848 kinds.insert(None);
849 }
850 kinds
851 }
852}
853
854impl AllLanguageSettings {
855 /// Returns the [`LanguageSettings`] for the language with the specified name.
856 pub fn language<'a>(
857 &'a self,
858 location: Option<SettingsLocation<'a>>,
859 language_name: Option<&LanguageName>,
860 cx: &'a App,
861 ) -> Cow<'a, LanguageSettings> {
862 let settings = language_name
863 .and_then(|name| self.languages.get(name))
864 .unwrap_or(&self.defaults);
865
866 let editorconfig_properties = location.and_then(|location| {
867 cx.global::<SettingsStore>()
868 .editorconfig_properties(location.worktree_id, location.path)
869 });
870 if let Some(editorconfig_properties) = editorconfig_properties {
871 let mut settings = settings.clone();
872 merge_with_editorconfig(&mut settings, &editorconfig_properties);
873 Cow::Owned(settings)
874 } else {
875 Cow::Borrowed(settings)
876 }
877 }
878
879 /// Returns whether inline completions are enabled for the given path.
880 pub fn inline_completions_enabled_for_path(&self, path: &Path) -> bool {
881 !self
882 .inline_completions
883 .disabled_globs
884 .iter()
885 .any(|glob| glob.is_match(path))
886 }
887
888 /// Returns whether inline completions are enabled for the given language and path.
889 pub fn inline_completions_enabled(
890 &self,
891 language: Option<&Arc<Language>>,
892 path: Option<&Path>,
893 cx: &App,
894 ) -> bool {
895 if let Some(path) = path {
896 if !self.inline_completions_enabled_for_path(path) {
897 return false;
898 }
899 }
900
901 self.language(None, language.map(|l| l.name()).as_ref(), cx)
902 .show_inline_completions
903 }
904}
905
906fn merge_with_editorconfig(settings: &mut LanguageSettings, cfg: &EditorconfigProperties) {
907 let tab_size = cfg.get::<IndentSize>().ok().and_then(|v| match v {
908 IndentSize::Value(u) => NonZeroU32::new(u as u32),
909 IndentSize::UseTabWidth => cfg.get::<TabWidth>().ok().and_then(|w| match w {
910 TabWidth::Value(u) => NonZeroU32::new(u as u32),
911 }),
912 });
913 let hard_tabs = cfg
914 .get::<IndentStyle>()
915 .map(|v| v.eq(&IndentStyle::Tabs))
916 .ok();
917 let ensure_final_newline_on_save = cfg
918 .get::<FinalNewline>()
919 .map(|v| match v {
920 FinalNewline::Value(b) => b,
921 })
922 .ok();
923 let remove_trailing_whitespace_on_save = cfg
924 .get::<TrimTrailingWs>()
925 .map(|v| match v {
926 TrimTrailingWs::Value(b) => b,
927 })
928 .ok();
929 fn merge<T>(target: &mut T, value: Option<T>) {
930 if let Some(value) = value {
931 *target = value;
932 }
933 }
934 merge(&mut settings.tab_size, tab_size);
935 merge(&mut settings.hard_tabs, hard_tabs);
936 merge(
937 &mut settings.remove_trailing_whitespace_on_save,
938 remove_trailing_whitespace_on_save,
939 );
940 merge(
941 &mut settings.ensure_final_newline_on_save,
942 ensure_final_newline_on_save,
943 );
944}
945
946/// The kind of an inlay hint.
947#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
948pub enum InlayHintKind {
949 /// An inlay hint for a type.
950 Type,
951 /// An inlay hint for a parameter.
952 Parameter,
953}
954
955impl InlayHintKind {
956 /// Returns the [`InlayHintKind`] from the given name.
957 ///
958 /// Returns `None` if `name` does not match any of the expected
959 /// string representations.
960 pub fn from_name(name: &str) -> Option<Self> {
961 match name {
962 "type" => Some(InlayHintKind::Type),
963 "parameter" => Some(InlayHintKind::Parameter),
964 _ => None,
965 }
966 }
967
968 /// Returns the name of this [`InlayHintKind`].
969 pub fn name(&self) -> &'static str {
970 match self {
971 InlayHintKind::Type => "type",
972 InlayHintKind::Parameter => "parameter",
973 }
974 }
975}
976
977impl settings::Settings for AllLanguageSettings {
978 const KEY: Option<&'static str> = None;
979
980 type FileContent = AllLanguageSettingsContent;
981
982 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
983 let default_value = sources.default;
984
985 // A default is provided for all settings.
986 let mut defaults: LanguageSettings =
987 serde_json::from_value(serde_json::to_value(&default_value.defaults)?)?;
988
989 let mut languages = HashMap::default();
990 for (language_name, settings) in &default_value.languages {
991 let mut language_settings = defaults.clone();
992 merge_settings(&mut language_settings, settings);
993 languages.insert(language_name.clone(), language_settings);
994 }
995
996 let mut copilot_enabled = default_value.features.as_ref().and_then(|f| f.copilot);
997 let mut inline_completion_provider = default_value
998 .features
999 .as_ref()
1000 .and_then(|f| f.inline_completion_provider);
1001 let mut completion_globs = default_value
1002 .inline_completions
1003 .as_ref()
1004 .and_then(|c| c.disabled_globs.as_ref())
1005 .ok_or_else(Self::missing_default)?;
1006
1007 let mut file_types: HashMap<Arc<str>, GlobSet> = HashMap::default();
1008
1009 for (language, suffixes) in &default_value.file_types {
1010 let mut builder = GlobSetBuilder::new();
1011
1012 for suffix in suffixes {
1013 builder.add(Glob::new(suffix)?);
1014 }
1015
1016 file_types.insert(language.clone(), builder.build()?);
1017 }
1018
1019 for user_settings in sources.customizations() {
1020 if let Some(copilot) = user_settings.features.as_ref().and_then(|f| f.copilot) {
1021 copilot_enabled = Some(copilot);
1022 }
1023 if let Some(provider) = user_settings
1024 .features
1025 .as_ref()
1026 .and_then(|f| f.inline_completion_provider)
1027 {
1028 inline_completion_provider = Some(provider);
1029 }
1030 if let Some(globs) = user_settings
1031 .inline_completions
1032 .as_ref()
1033 .and_then(|f| f.disabled_globs.as_ref())
1034 {
1035 completion_globs = globs;
1036 }
1037
1038 // A user's global settings override the default global settings and
1039 // all default language-specific settings.
1040 merge_settings(&mut defaults, &user_settings.defaults);
1041 for language_settings in languages.values_mut() {
1042 merge_settings(language_settings, &user_settings.defaults);
1043 }
1044
1045 // A user's language-specific settings override default language-specific settings.
1046 for (language_name, user_language_settings) in &user_settings.languages {
1047 merge_settings(
1048 languages
1049 .entry(language_name.clone())
1050 .or_insert_with(|| defaults.clone()),
1051 user_language_settings,
1052 );
1053 }
1054
1055 for (language, suffixes) in &user_settings.file_types {
1056 let mut builder = GlobSetBuilder::new();
1057
1058 let default_value = default_value.file_types.get(&language.clone());
1059
1060 // Merge the default value with the user's value.
1061 if let Some(suffixes) = default_value {
1062 for suffix in suffixes {
1063 builder.add(Glob::new(suffix)?);
1064 }
1065 }
1066
1067 for suffix in suffixes {
1068 builder.add(Glob::new(suffix)?);
1069 }
1070
1071 file_types.insert(language.clone(), builder.build()?);
1072 }
1073 }
1074
1075 Ok(Self {
1076 inline_completions: InlineCompletionSettings {
1077 provider: if let Some(provider) = inline_completion_provider {
1078 provider
1079 } else if copilot_enabled.unwrap_or(true) {
1080 InlineCompletionProvider::Copilot
1081 } else {
1082 InlineCompletionProvider::None
1083 },
1084 disabled_globs: completion_globs
1085 .iter()
1086 .filter_map(|g| Some(globset::Glob::new(g).ok()?.compile_matcher()))
1087 .collect(),
1088 },
1089 defaults,
1090 languages,
1091 file_types,
1092 })
1093 }
1094
1095 fn json_schema(
1096 generator: &mut schemars::gen::SchemaGenerator,
1097 params: &settings::SettingsJsonSchemaParams,
1098 _: &App,
1099 ) -> schemars::schema::RootSchema {
1100 let mut root_schema = generator.root_schema_for::<Self::FileContent>();
1101
1102 // Create a schema for a 'languages overrides' object, associating editor
1103 // settings with specific languages.
1104 assert!(root_schema
1105 .definitions
1106 .contains_key("LanguageSettingsContent"));
1107
1108 let languages_object_schema = SchemaObject {
1109 instance_type: Some(InstanceType::Object.into()),
1110 object: Some(Box::new(ObjectValidation {
1111 properties: params
1112 .language_names
1113 .iter()
1114 .map(|name| {
1115 (
1116 name.clone(),
1117 Schema::new_ref("#/definitions/LanguageSettingsContent".into()),
1118 )
1119 })
1120 .collect(),
1121 ..Default::default()
1122 })),
1123 ..Default::default()
1124 };
1125
1126 root_schema
1127 .definitions
1128 .extend([("Languages".into(), languages_object_schema.into())]);
1129
1130 add_references_to_properties(
1131 &mut root_schema,
1132 &[("languages", "#/definitions/Languages")],
1133 );
1134
1135 root_schema
1136 }
1137}
1138
1139fn merge_settings(settings: &mut LanguageSettings, src: &LanguageSettingsContent) {
1140 fn merge<T>(target: &mut T, value: Option<T>) {
1141 if let Some(value) = value {
1142 *target = value;
1143 }
1144 }
1145
1146 merge(&mut settings.tab_size, src.tab_size);
1147 settings.tab_size = settings
1148 .tab_size
1149 .clamp(NonZeroU32::new(1).unwrap(), NonZeroU32::new(16).unwrap());
1150
1151 merge(&mut settings.hard_tabs, src.hard_tabs);
1152 merge(&mut settings.soft_wrap, src.soft_wrap);
1153 merge(&mut settings.use_autoclose, src.use_autoclose);
1154 merge(&mut settings.use_auto_surround, src.use_auto_surround);
1155 merge(&mut settings.use_on_type_format, src.use_on_type_format);
1156 merge(&mut settings.auto_indent_on_paste, src.auto_indent_on_paste);
1157 merge(
1158 &mut settings.always_treat_brackets_as_autoclosed,
1159 src.always_treat_brackets_as_autoclosed,
1160 );
1161 merge(&mut settings.show_wrap_guides, src.show_wrap_guides);
1162 merge(&mut settings.wrap_guides, src.wrap_guides.clone());
1163 merge(&mut settings.indent_guides, src.indent_guides);
1164 merge(
1165 &mut settings.code_actions_on_format,
1166 src.code_actions_on_format.clone(),
1167 );
1168 merge(&mut settings.linked_edits, src.linked_edits);
1169 merge(&mut settings.tasks, src.tasks.clone());
1170
1171 merge(
1172 &mut settings.preferred_line_length,
1173 src.preferred_line_length,
1174 );
1175 merge(&mut settings.formatter, src.formatter.clone());
1176 merge(&mut settings.prettier, src.prettier.clone());
1177 merge(&mut settings.format_on_save, src.format_on_save.clone());
1178 merge(
1179 &mut settings.remove_trailing_whitespace_on_save,
1180 src.remove_trailing_whitespace_on_save,
1181 );
1182 merge(
1183 &mut settings.ensure_final_newline_on_save,
1184 src.ensure_final_newline_on_save,
1185 );
1186 merge(
1187 &mut settings.enable_language_server,
1188 src.enable_language_server,
1189 );
1190 merge(&mut settings.language_servers, src.language_servers.clone());
1191 merge(
1192 &mut settings.show_inline_completions,
1193 src.show_inline_completions,
1194 );
1195 merge(
1196 &mut settings.inline_completions_disabled_in,
1197 src.inline_completions_disabled_in.clone(),
1198 );
1199 merge(&mut settings.show_whitespaces, src.show_whitespaces);
1200 merge(
1201 &mut settings.extend_comment_on_newline,
1202 src.extend_comment_on_newline,
1203 );
1204 merge(&mut settings.inlay_hints, src.inlay_hints);
1205 merge(
1206 &mut settings.show_completions_on_input,
1207 src.show_completions_on_input,
1208 );
1209 merge(
1210 &mut settings.show_completion_documentation,
1211 src.show_completion_documentation,
1212 );
1213}
1214
1215/// Allows to enable/disable formatting with Prettier
1216/// and configure default Prettier, used when no project-level Prettier installation is found.
1217/// Prettier formatting is disabled by default.
1218#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1219pub struct PrettierSettings {
1220 /// Enables or disables formatting with Prettier for a given language.
1221 #[serde(default)]
1222 pub allowed: bool,
1223
1224 /// Forces Prettier integration to use a specific parser name when formatting files with the language.
1225 #[serde(default)]
1226 pub parser: Option<String>,
1227
1228 /// Forces Prettier integration to use specific plugins when formatting files with the language.
1229 /// The default Prettier will be installed with these plugins.
1230 #[serde(default)]
1231 pub plugins: HashSet<String>,
1232
1233 /// Default Prettier options, in the format as in package.json section for Prettier.
1234 /// If project installs Prettier via its package.json, these options will be ignored.
1235 #[serde(flatten)]
1236 pub options: HashMap<String, serde_json::Value>,
1237}
1238
1239#[cfg(test)]
1240mod tests {
1241 use super::*;
1242
1243 #[test]
1244 fn test_formatter_deserialization() {
1245 let raw_auto = "{\"formatter\": \"auto\"}";
1246 let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
1247 assert_eq!(settings.formatter, Some(SelectedFormatter::Auto));
1248 let raw = "{\"formatter\": \"language_server\"}";
1249 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1250 assert_eq!(
1251 settings.formatter,
1252 Some(SelectedFormatter::List(FormatterList(
1253 Formatter::LanguageServer { name: None }.into()
1254 )))
1255 );
1256 let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
1257 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1258 assert_eq!(
1259 settings.formatter,
1260 Some(SelectedFormatter::List(FormatterList(
1261 vec![Formatter::LanguageServer { name: None }].into()
1262 )))
1263 );
1264 let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"prettier\"]}";
1265 let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1266 assert_eq!(
1267 settings.formatter,
1268 Some(SelectedFormatter::List(FormatterList(
1269 vec![
1270 Formatter::LanguageServer { name: None },
1271 Formatter::Prettier
1272 ]
1273 .into()
1274 )))
1275 );
1276 }
1277
1278 #[test]
1279 fn test_formatter_deserialization_invalid() {
1280 let raw_auto = "{\"formatter\": {}}";
1281 let result: Result<LanguageSettingsContent, _> = serde_json::from_str(raw_auto);
1282 assert!(result.is_err());
1283 }
1284
1285 #[test]
1286 pub fn test_resolve_language_servers() {
1287 fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
1288 names
1289 .iter()
1290 .copied()
1291 .map(|name| LanguageServerName(name.to_string().into()))
1292 .collect::<Vec<_>>()
1293 }
1294
1295 let available_language_servers = language_server_names(&[
1296 "typescript-language-server",
1297 "biome",
1298 "deno",
1299 "eslint",
1300 "tailwind",
1301 ]);
1302
1303 // A value of just `["..."]` is the same as taking all of the available language servers.
1304 assert_eq!(
1305 LanguageSettings::resolve_language_servers(
1306 &[LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()],
1307 &available_language_servers,
1308 ),
1309 available_language_servers
1310 );
1311
1312 // Referencing one of the available language servers will change its order.
1313 assert_eq!(
1314 LanguageSettings::resolve_language_servers(
1315 &[
1316 "biome".into(),
1317 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into(),
1318 "deno".into()
1319 ],
1320 &available_language_servers
1321 ),
1322 language_server_names(&[
1323 "biome",
1324 "typescript-language-server",
1325 "eslint",
1326 "tailwind",
1327 "deno",
1328 ])
1329 );
1330
1331 // Negating an available language server removes it from the list.
1332 assert_eq!(
1333 LanguageSettings::resolve_language_servers(
1334 &[
1335 "deno".into(),
1336 "!typescript-language-server".into(),
1337 "!biome".into(),
1338 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1339 ],
1340 &available_language_servers
1341 ),
1342 language_server_names(&["deno", "eslint", "tailwind"])
1343 );
1344
1345 // Adding a language server not in the list of available language servers adds it to the list.
1346 assert_eq!(
1347 LanguageSettings::resolve_language_servers(
1348 &[
1349 "my-cool-language-server".into(),
1350 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1351 ],
1352 &available_language_servers
1353 ),
1354 language_server_names(&[
1355 "my-cool-language-server",
1356 "typescript-language-server",
1357 "biome",
1358 "deno",
1359 "eslint",
1360 "tailwind",
1361 ])
1362 );
1363 }
1364}