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