1//! Provides `language`-related settings.
2
3use crate::{File, Language};
4use anyhow::Result;
5use collections::{HashMap, HashSet};
6use globset::GlobMatcher;
7use gpui::AppContext;
8use schemars::{
9 schema::{InstanceType, ObjectValidation, Schema, SchemaObject},
10 JsonSchema,
11};
12use serde::{Deserialize, Serialize};
13use settings::Settings;
14use std::{num::NonZeroU32, path::Path, sync::Arc};
15
16/// Initializes the language settings.
17pub fn init(cx: &mut AppContext) {
18 AllLanguageSettings::register(cx);
19}
20
21/// Returns the settings for the specified language from the provided file.
22pub fn language_settings<'a>(
23 language: Option<&Arc<Language>>,
24 file: Option<&Arc<dyn File>>,
25 cx: &'a AppContext,
26) -> &'a LanguageSettings {
27 let language_name = language.map(|l| l.name());
28 all_language_settings(file, cx).language(language_name.as_deref())
29}
30
31/// Returns the settings for all languages from the provided file.
32pub fn all_language_settings<'a>(
33 file: Option<&Arc<dyn File>>,
34 cx: &'a AppContext,
35) -> &'a AllLanguageSettings {
36 let location = file.map(|f| (f.worktree_id(), f.path().as_ref()));
37 AllLanguageSettings::get(location, cx)
38}
39
40/// The settings for all languages.
41#[derive(Debug, Clone)]
42pub struct AllLanguageSettings {
43 /// The settings for GitHub Copilot.
44 pub copilot: CopilotSettings,
45 defaults: LanguageSettings,
46 languages: HashMap<Arc<str>, LanguageSettings>,
47}
48
49/// The settings for a particular language.
50#[derive(Debug, Clone, Deserialize)]
51pub struct LanguageSettings {
52 /// How many columns a tab should occupy.
53 pub tab_size: NonZeroU32,
54 /// Whether to indent lines using tab characters, as opposed to multiple
55 /// spaces.
56 pub hard_tabs: bool,
57 /// How to soft-wrap long lines of text.
58 pub soft_wrap: SoftWrap,
59 /// The column at which to soft-wrap lines, for buffers where soft-wrap
60 /// is enabled.
61 pub preferred_line_length: u32,
62 /// Whether to show wrap guides in the editor. Setting this to true will
63 /// show a guide at the 'preferred_line_length' value if softwrap is set to
64 /// 'preferred_line_length', and will show any additional guides as specified
65 /// by the 'wrap_guides' setting.
66 pub show_wrap_guides: bool,
67 /// Character counts at which to show wrap guides in the editor.
68 pub wrap_guides: Vec<usize>,
69 /// Whether or not to perform a buffer format before saving.
70 pub format_on_save: FormatOnSave,
71 /// Whether or not to remove any trailing whitespace from lines of a buffer
72 /// before saving it.
73 pub remove_trailing_whitespace_on_save: bool,
74 /// Whether or not to ensure there's a single newline at the end of a buffer
75 /// when saving it.
76 pub ensure_final_newline_on_save: bool,
77 /// How to perform a buffer format.
78 pub formatter: Formatter,
79 /// Zed's Prettier integration settings.
80 /// If Prettier is enabled, Zed will use this its Prettier instance for any applicable file, if
81 /// the project has no other Prettier installed.
82 pub prettier: HashMap<String, serde_json::Value>,
83 /// Whether to use language servers to provide code intelligence.
84 pub enable_language_server: bool,
85 /// Controls whether Copilot provides suggestion immediately (true)
86 /// or waits for a `copilot::Toggle` (false).
87 pub show_copilot_suggestions: bool,
88 /// Whether to show tabs and spaces in the editor.
89 pub show_whitespaces: ShowWhitespaceSetting,
90 /// Whether to start a new line with a comment when a previous line is a comment as well.
91 pub extend_comment_on_newline: bool,
92 /// Inlay hint related settings.
93 pub inlay_hints: InlayHintSettings,
94 /// Whether to automatically close brackets.
95 pub use_autoclose: bool,
96 /// Which code actions to run on save
97 pub code_actions_on_format: HashMap<String, bool>,
98}
99
100/// The settings for [GitHub Copilot](https://github.com/features/copilot).
101#[derive(Clone, Debug, Default)]
102pub struct CopilotSettings {
103 /// Whether Copilot is enabled.
104 pub feature_enabled: bool,
105 /// A list of globs representing files that Copilot should be disabled for.
106 pub disabled_globs: Vec<GlobMatcher>,
107}
108
109/// The settings for all languages.
110#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
111pub struct AllLanguageSettingsContent {
112 /// The settings for enabling/disabling features.
113 #[serde(default)]
114 pub features: Option<FeaturesContent>,
115 /// The settings for GitHub Copilot.
116 #[serde(default)]
117 pub copilot: Option<CopilotSettingsContent>,
118 /// The default language settings.
119 #[serde(flatten)]
120 pub defaults: LanguageSettingsContent,
121 /// The settings for individual languages.
122 #[serde(default, alias = "language_overrides")]
123 pub languages: HashMap<Arc<str>, LanguageSettingsContent>,
124}
125
126/// The settings for a particular language.
127#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
128pub struct LanguageSettingsContent {
129 /// How many columns a tab should occupy.
130 ///
131 /// Default: 4
132 #[serde(default)]
133 pub tab_size: Option<NonZeroU32>,
134 /// Whether to indent lines using tab characters, as opposed to multiple
135 /// spaces.
136 ///
137 /// Default: false
138 #[serde(default)]
139 pub hard_tabs: Option<bool>,
140 /// How to soft-wrap long lines of text.
141 ///
142 /// Default: none
143 #[serde(default)]
144 pub soft_wrap: Option<SoftWrap>,
145 /// The column at which to soft-wrap lines, for buffers where soft-wrap
146 /// is enabled.
147 ///
148 /// Default: 80
149 #[serde(default)]
150 pub preferred_line_length: Option<u32>,
151 /// Whether to show wrap guides in the editor. Setting this to true will
152 /// show a guide at the 'preferred_line_length' value if softwrap is set to
153 /// 'preferred_line_length', and will show any additional guides as specified
154 /// by the 'wrap_guides' setting.
155 ///
156 /// Default: true
157 #[serde(default)]
158 pub show_wrap_guides: Option<bool>,
159 /// Character counts at which to show wrap guides in the editor.
160 ///
161 /// Default: []
162 #[serde(default)]
163 pub wrap_guides: Option<Vec<usize>>,
164 /// Whether or not to perform a buffer format before saving.
165 ///
166 /// Default: on
167 #[serde(default)]
168 pub format_on_save: Option<FormatOnSave>,
169 /// Whether or not to remove any trailing whitespace from lines of a buffer
170 /// before saving it.
171 ///
172 /// Default: true
173 #[serde(default)]
174 pub remove_trailing_whitespace_on_save: Option<bool>,
175 /// Whether or not to ensure there's a single newline at the end of a buffer
176 /// when saving it.
177 ///
178 /// Default: true
179 #[serde(default)]
180 pub ensure_final_newline_on_save: Option<bool>,
181 /// How to perform a buffer format.
182 ///
183 /// Default: auto
184 #[serde(default)]
185 pub formatter: Option<Formatter>,
186 /// Zed's Prettier integration settings.
187 /// If Prettier is enabled, Zed will use this its Prettier instance for any applicable file, if
188 /// the project has no other Prettier installed.
189 ///
190 /// Default: {}
191 #[serde(default)]
192 pub prettier: Option<HashMap<String, serde_json::Value>>,
193 /// Whether to use language servers to provide code intelligence.
194 ///
195 /// Default: true
196 #[serde(default)]
197 pub enable_language_server: Option<bool>,
198 /// Controls whether Copilot provides suggestion immediately (true)
199 /// or waits for a `copilot::Toggle` (false).
200 ///
201 /// Default: true
202 #[serde(default)]
203 pub show_copilot_suggestions: Option<bool>,
204 /// Whether to show tabs and spaces in the editor.
205 #[serde(default)]
206 pub show_whitespaces: Option<ShowWhitespaceSetting>,
207 /// Whether to start a new line with a comment when a previous line is a comment as well.
208 ///
209 /// Default: true
210 #[serde(default)]
211 pub extend_comment_on_newline: Option<bool>,
212 /// Inlay hint related settings.
213 #[serde(default)]
214 pub inlay_hints: Option<InlayHintSettings>,
215 /// Whether to automatically type closing characters for you. For example,
216 /// when you type (, Zed will automatically add a closing ) at the correct position.
217 ///
218 /// Default: true
219 pub use_autoclose: Option<bool>,
220
221 /// Which code actions to run on save
222 ///
223 /// Default: {} (or {"source.organizeImports": true} for Go).
224 pub code_actions_on_format: Option<HashMap<String, bool>>,
225}
226
227/// The contents of the GitHub Copilot settings.
228#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
229pub struct CopilotSettingsContent {
230 /// A list of globs representing files that Copilot should be disabled for.
231 #[serde(default)]
232 pub disabled_globs: Option<Vec<String>>,
233}
234
235/// The settings for enabling/disabling features.
236#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
237#[serde(rename_all = "snake_case")]
238pub struct FeaturesContent {
239 /// Whether the GitHub Copilot feature is enabled.
240 pub copilot: Option<bool>,
241}
242
243/// Controls the soft-wrapping behavior in the editor.
244#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
245#[serde(rename_all = "snake_case")]
246pub enum SoftWrap {
247 /// Do not soft wrap.
248 None,
249 /// Soft wrap lines that overflow the editor
250 EditorWidth,
251 /// Soft wrap lines at the preferred line length
252 PreferredLineLength,
253}
254
255/// Controls the behavior of formatting files when they are saved.
256#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
257#[serde(rename_all = "snake_case")]
258pub enum FormatOnSave {
259 /// Files should be formatted on save.
260 On,
261 /// Files should not be formatted on save.
262 Off,
263 /// Files should be formatted using the current language server.
264 LanguageServer,
265 /// The external program to use to format the files on save.
266 External {
267 /// The external program to run.
268 command: Arc<str>,
269 /// The arguments to pass to the program.
270 arguments: Arc<[String]>,
271 },
272}
273
274/// Controls how whitespace should be displayedin the editor.
275#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
276#[serde(rename_all = "snake_case")]
277pub enum ShowWhitespaceSetting {
278 /// Draw whitespace only for the selected text.
279 Selection,
280 /// Do not draw any tabs or spaces.
281 None,
282 /// Draw all invisible symbols.
283 All,
284}
285
286/// Controls which formatter should be used when formatting code.
287#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
288#[serde(rename_all = "snake_case")]
289pub enum Formatter {
290 /// Format files using Zed's Prettier integration (if applicable),
291 /// or falling back to formatting via language server.
292 #[default]
293 Auto,
294 /// Format code using the current language server.
295 LanguageServer,
296 /// Format code using Zed's Prettier integration.
297 Prettier,
298 /// Format code using an external command.
299 External {
300 /// The external program to run.
301 command: Arc<str>,
302 /// The arguments to pass to the program.
303 arguments: Arc<[String]>,
304 },
305}
306
307/// The settings for inlay hints.
308#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
309pub struct InlayHintSettings {
310 /// Global switch to toggle hints on and off.
311 ///
312 /// Default: false
313 #[serde(default)]
314 pub enabled: bool,
315 /// Whether type hints should be shown.
316 ///
317 /// Default: true
318 #[serde(default = "default_true")]
319 pub show_type_hints: bool,
320 /// Whether parameter hints should be shown.
321 ///
322 /// Default: true
323 #[serde(default = "default_true")]
324 pub show_parameter_hints: bool,
325 /// Whether other hints should be shown.
326 ///
327 /// Default: true
328 #[serde(default = "default_true")]
329 pub show_other_hints: bool,
330}
331
332fn default_true() -> bool {
333 true
334}
335
336impl InlayHintSettings {
337 /// Returns the kinds of inlay hints that are enabled based on the settings.
338 pub fn enabled_inlay_hint_kinds(&self) -> HashSet<Option<InlayHintKind>> {
339 let mut kinds = HashSet::default();
340 if self.show_type_hints {
341 kinds.insert(Some(InlayHintKind::Type));
342 }
343 if self.show_parameter_hints {
344 kinds.insert(Some(InlayHintKind::Parameter));
345 }
346 if self.show_other_hints {
347 kinds.insert(None);
348 }
349 kinds
350 }
351}
352
353impl AllLanguageSettings {
354 /// Returns the [`LanguageSettings`] for the language with the specified name.
355 pub fn language<'a>(&'a self, language_name: Option<&str>) -> &'a LanguageSettings {
356 if let Some(name) = language_name {
357 if let Some(overrides) = self.languages.get(name) {
358 return overrides;
359 }
360 }
361 &self.defaults
362 }
363
364 /// Returns whether GitHub Copilot is enabled for the given path.
365 pub fn copilot_enabled_for_path(&self, path: &Path) -> bool {
366 !self
367 .copilot
368 .disabled_globs
369 .iter()
370 .any(|glob| glob.is_match(path))
371 }
372
373 /// Returns whether GitHub Copilot is enabled for the given language and path.
374 pub fn copilot_enabled(&self, language: Option<&Arc<Language>>, path: Option<&Path>) -> bool {
375 if !self.copilot.feature_enabled {
376 return false;
377 }
378
379 if let Some(path) = path {
380 if !self.copilot_enabled_for_path(path) {
381 return false;
382 }
383 }
384
385 self.language(language.map(|l| l.name()).as_deref())
386 .show_copilot_suggestions
387 }
388}
389
390/// The kind of an inlay hint.
391#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
392pub enum InlayHintKind {
393 /// An inlay hint for a type.
394 Type,
395 /// An inlay hint for a parameter.
396 Parameter,
397}
398
399impl InlayHintKind {
400 /// Returns the [`InlayHintKind`] from the given name.
401 ///
402 /// Returns `None` if `name` does not match any of the expected
403 /// string representations.
404 pub fn from_name(name: &str) -> Option<Self> {
405 match name {
406 "type" => Some(InlayHintKind::Type),
407 "parameter" => Some(InlayHintKind::Parameter),
408 _ => None,
409 }
410 }
411
412 /// Returns the name of this [`InlayHintKind`].
413 pub fn name(&self) -> &'static str {
414 match self {
415 InlayHintKind::Type => "type",
416 InlayHintKind::Parameter => "parameter",
417 }
418 }
419}
420
421impl settings::Settings for AllLanguageSettings {
422 const KEY: Option<&'static str> = None;
423
424 type FileContent = AllLanguageSettingsContent;
425
426 fn load(
427 default_value: &Self::FileContent,
428 user_settings: &[&Self::FileContent],
429 _: &mut AppContext,
430 ) -> Result<Self> {
431 // A default is provided for all settings.
432 let mut defaults: LanguageSettings =
433 serde_json::from_value(serde_json::to_value(&default_value.defaults)?)?;
434
435 let mut languages = HashMap::default();
436 for (language_name, settings) in &default_value.languages {
437 let mut language_settings = defaults.clone();
438 merge_settings(&mut language_settings, settings);
439 languages.insert(language_name.clone(), language_settings);
440 }
441
442 let mut copilot_enabled = default_value
443 .features
444 .as_ref()
445 .and_then(|f| f.copilot)
446 .ok_or_else(Self::missing_default)?;
447 let mut copilot_globs = default_value
448 .copilot
449 .as_ref()
450 .and_then(|c| c.disabled_globs.as_ref())
451 .ok_or_else(Self::missing_default)?;
452
453 for user_settings in user_settings {
454 if let Some(copilot) = user_settings.features.as_ref().and_then(|f| f.copilot) {
455 copilot_enabled = copilot;
456 }
457 if let Some(globs) = user_settings
458 .copilot
459 .as_ref()
460 .and_then(|f| f.disabled_globs.as_ref())
461 {
462 copilot_globs = globs;
463 }
464
465 // A user's global settings override the default global settings and
466 // all default language-specific settings.
467 merge_settings(&mut defaults, &user_settings.defaults);
468 for language_settings in languages.values_mut() {
469 merge_settings(language_settings, &user_settings.defaults);
470 }
471
472 // A user's language-specific settings override default language-specific settings.
473 for (language_name, user_language_settings) in &user_settings.languages {
474 merge_settings(
475 languages
476 .entry(language_name.clone())
477 .or_insert_with(|| defaults.clone()),
478 user_language_settings,
479 );
480 }
481 }
482
483 Ok(Self {
484 copilot: CopilotSettings {
485 feature_enabled: copilot_enabled,
486 disabled_globs: copilot_globs
487 .iter()
488 .filter_map(|g| Some(globset::Glob::new(g).ok()?.compile_matcher()))
489 .collect(),
490 },
491 defaults,
492 languages,
493 })
494 }
495
496 fn json_schema(
497 generator: &mut schemars::gen::SchemaGenerator,
498 params: &settings::SettingsJsonSchemaParams,
499 _: &AppContext,
500 ) -> schemars::schema::RootSchema {
501 let mut root_schema = generator.root_schema_for::<Self::FileContent>();
502
503 // Create a schema for a 'languages overrides' object, associating editor
504 // settings with specific languages.
505 assert!(root_schema
506 .definitions
507 .contains_key("LanguageSettingsContent"));
508
509 let languages_object_schema = SchemaObject {
510 instance_type: Some(InstanceType::Object.into()),
511 object: Some(Box::new(ObjectValidation {
512 properties: params
513 .language_names
514 .iter()
515 .map(|name| {
516 (
517 name.clone(),
518 Schema::new_ref("#/definitions/LanguageSettingsContent".into()),
519 )
520 })
521 .collect(),
522 ..Default::default()
523 })),
524 ..Default::default()
525 };
526
527 root_schema
528 .definitions
529 .extend([("Languages".into(), languages_object_schema.into())]);
530
531 root_schema
532 .schema
533 .object
534 .as_mut()
535 .unwrap()
536 .properties
537 .extend([
538 (
539 "languages".to_owned(),
540 Schema::new_ref("#/definitions/Languages".into()),
541 ),
542 // For backward compatibility
543 (
544 "language_overrides".to_owned(),
545 Schema::new_ref("#/definitions/Languages".into()),
546 ),
547 ]);
548
549 root_schema
550 }
551}
552
553fn merge_settings(settings: &mut LanguageSettings, src: &LanguageSettingsContent) {
554 merge(&mut settings.tab_size, src.tab_size);
555 merge(&mut settings.hard_tabs, src.hard_tabs);
556 merge(&mut settings.soft_wrap, src.soft_wrap);
557 merge(&mut settings.use_autoclose, src.use_autoclose);
558 merge(&mut settings.show_wrap_guides, src.show_wrap_guides);
559 merge(&mut settings.wrap_guides, src.wrap_guides.clone());
560 merge(
561 &mut settings.code_actions_on_format,
562 src.code_actions_on_format.clone(),
563 );
564
565 merge(
566 &mut settings.preferred_line_length,
567 src.preferred_line_length,
568 );
569 merge(&mut settings.formatter, src.formatter.clone());
570 merge(&mut settings.prettier, src.prettier.clone());
571 merge(&mut settings.format_on_save, src.format_on_save.clone());
572 merge(
573 &mut settings.remove_trailing_whitespace_on_save,
574 src.remove_trailing_whitespace_on_save,
575 );
576 merge(
577 &mut settings.ensure_final_newline_on_save,
578 src.ensure_final_newline_on_save,
579 );
580 merge(
581 &mut settings.enable_language_server,
582 src.enable_language_server,
583 );
584 merge(
585 &mut settings.show_copilot_suggestions,
586 src.show_copilot_suggestions,
587 );
588 merge(&mut settings.show_whitespaces, src.show_whitespaces);
589 merge(
590 &mut settings.extend_comment_on_newline,
591 src.extend_comment_on_newline,
592 );
593 merge(&mut settings.inlay_hints, src.inlay_hints);
594 fn merge<T>(target: &mut T, value: Option<T>) {
595 if let Some(value) = value {
596 *target = value;
597 }
598 }
599}