1//! Provides `language`-related settings.
2
3use crate::{File, Language, LanguageName, LanguageServerName};
4use collections::{FxHashMap, HashMap, HashSet};
5use ec4rs::{
6 Properties as EditorconfigProperties,
7 property::{FinalNewline, IndentSize, IndentStyle, MaxLineLen, TabWidth, TrimTrailingWs},
8};
9use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
10use gpui::{App, Modifiers, SharedString};
11use itertools::{Either, Itertools};
12use settings::IntoGpui;
13
14pub use settings::{
15 CompletionSettingsContent, EditPredictionProvider, EditPredictionsMode, FormatOnSave,
16 Formatter, FormatterList, InlayHintKind, LanguageSettingsContent, LspInsertMode,
17 RewrapBehavior, ShowWhitespaceSetting, SoftWrap, WordsCompletionMode,
18};
19use settings::{RegisterSetting, Settings, SettingsLocation, SettingsStore};
20use shellexpand;
21use std::{borrow::Cow, num::NonZeroU32, path::Path, sync::Arc};
22
23/// Returns the settings for the specified language from the provided file.
24pub fn language_settings<'a>(
25 language: Option<LanguageName>,
26 file: Option<&'a Arc<dyn File>>,
27 cx: &'a App,
28) -> Cow<'a, LanguageSettings> {
29 let location = file.map(|f| SettingsLocation {
30 worktree_id: f.worktree_id(cx),
31 path: f.path().as_ref(),
32 });
33 AllLanguageSettings::get(location, cx).language(location, language.as_ref(), cx)
34}
35
36/// Returns the settings for all languages from the provided file.
37pub fn all_language_settings<'a>(
38 file: Option<&'a Arc<dyn File>>,
39 cx: &'a App,
40) -> &'a AllLanguageSettings {
41 let location = file.map(|f| SettingsLocation {
42 worktree_id: f.worktree_id(cx),
43 path: f.path().as_ref(),
44 });
45 AllLanguageSettings::get(location, cx)
46}
47
48/// The settings for all languages.
49#[derive(Debug, Clone, RegisterSetting)]
50pub struct AllLanguageSettings {
51 /// The edit prediction settings.
52 pub edit_predictions: EditPredictionSettings,
53 pub defaults: LanguageSettings,
54 languages: HashMap<LanguageName, LanguageSettings>,
55 pub file_types: FxHashMap<Arc<str>, (GlobSet, Vec<String>)>,
56}
57
58#[derive(Debug, Clone, PartialEq)]
59pub struct WhitespaceMap {
60 pub space: SharedString,
61 pub tab: SharedString,
62}
63
64/// The settings for a particular language.
65#[derive(Debug, Clone, PartialEq)]
66pub struct LanguageSettings {
67 /// How many columns a tab should occupy.
68 pub tab_size: NonZeroU32,
69 /// Whether to indent lines using tab characters, as opposed to multiple
70 /// spaces.
71 pub hard_tabs: bool,
72 /// How to soft-wrap long lines of text.
73 pub soft_wrap: settings::SoftWrap,
74 /// The column at which to soft-wrap lines, for buffers where soft-wrap
75 /// is enabled.
76 pub preferred_line_length: u32,
77 /// Whether to show wrap guides (vertical rulers) in the editor.
78 /// Setting this to true will show a guide at the 'preferred_line_length' value
79 /// if softwrap is set to 'preferred_line_length', and will show any
80 /// additional guides as specified by the 'wrap_guides' setting.
81 pub show_wrap_guides: bool,
82 /// Character counts at which to show wrap guides (vertical rulers) in the editor.
83 pub wrap_guides: Vec<usize>,
84 /// Indent guide related settings.
85 pub indent_guides: IndentGuideSettings,
86 /// Whether or not to perform a buffer format before saving.
87 pub format_on_save: FormatOnSave,
88 /// Whether or not to remove any trailing whitespace from lines of a buffer
89 /// before saving it.
90 pub remove_trailing_whitespace_on_save: bool,
91 /// Whether or not to ensure there's a single newline at the end of a buffer
92 /// when saving it.
93 pub ensure_final_newline_on_save: bool,
94 /// How to perform a buffer format.
95 pub formatter: settings::FormatterList,
96 /// Zed's Prettier integration settings.
97 pub prettier: PrettierSettings,
98 /// Whether to automatically close JSX tags.
99 pub jsx_tag_auto_close: bool,
100 /// Whether to use language servers to provide code intelligence.
101 pub enable_language_server: bool,
102 /// The list of language servers to use (or disable) for this language.
103 ///
104 /// This array should consist of language server IDs, as well as the following
105 /// special tokens:
106 /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
107 /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
108 pub language_servers: Vec<String>,
109 /// Controls where the `editor::Rewrap` action is allowed for this language.
110 ///
111 /// Note: This setting has no effect in Vim mode, as rewrap is already
112 /// allowed everywhere.
113 pub allow_rewrap: RewrapBehavior,
114 /// Controls whether edit predictions are shown immediately (true)
115 /// or manually by triggering `editor::ShowEditPrediction` (false).
116 pub show_edit_predictions: bool,
117 /// Controls whether edit predictions are shown in the given language
118 /// scopes.
119 pub edit_predictions_disabled_in: Vec<String>,
120 /// Whether to show tabs and spaces in the editor.
121 pub show_whitespaces: settings::ShowWhitespaceSetting,
122 /// Visible characters used to render whitespace when show_whitespaces is enabled.
123 pub whitespace_map: WhitespaceMap,
124 /// Whether to start a new line with a comment when a previous line is a comment as well.
125 pub extend_comment_on_newline: bool,
126 /// Whether to continue markdown lists when pressing enter.
127 pub extend_list_on_newline: bool,
128 /// Whether to indent list items when pressing tab after a list marker.
129 pub indent_list_on_tab: bool,
130 /// Inlay hint related settings.
131 pub inlay_hints: InlayHintSettings,
132 /// Whether to automatically close brackets.
133 pub use_autoclose: bool,
134 /// Whether to automatically surround text with brackets.
135 pub use_auto_surround: bool,
136 /// Whether to use additional LSP queries to format (and amend) the code after
137 /// every "trigger" symbol input, defined by LSP server capabilities.
138 pub use_on_type_format: bool,
139 /// Whether indentation should be adjusted based on the context whilst typing.
140 pub auto_indent: bool,
141 /// Whether indentation of pasted content should be adjusted based on the context.
142 pub auto_indent_on_paste: bool,
143 /// Controls how the editor handles the autoclosed characters.
144 pub always_treat_brackets_as_autoclosed: bool,
145 /// Which code actions to run on save
146 pub code_actions_on_format: HashMap<String, bool>,
147 /// Whether to perform linked edits
148 pub linked_edits: bool,
149 /// Task configuration for this language.
150 pub tasks: LanguageTaskSettings,
151 /// Whether to pop the completions menu while typing in an editor without
152 /// explicitly requesting it.
153 pub show_completions_on_input: bool,
154 /// Whether to display inline and alongside documentation for items in the
155 /// completions menu.
156 pub show_completion_documentation: bool,
157 /// Completion settings for this language.
158 pub completions: CompletionSettings,
159 /// Preferred debuggers for this language.
160 pub debuggers: Vec<String>,
161 /// Whether to enable word diff highlighting in the editor.
162 ///
163 /// When enabled, changed words within modified lines are highlighted
164 /// to show exactly what changed.
165 ///
166 /// Default: `true`
167 pub word_diff_enabled: bool,
168 /// Whether to use tree-sitter bracket queries to detect and colorize the brackets in the editor.
169 pub colorize_brackets: bool,
170}
171
172#[derive(Debug, Clone, PartialEq)]
173pub struct CompletionSettings {
174 /// Controls how words are completed.
175 /// For large documents, not all words may be fetched for completion.
176 ///
177 /// Default: `fallback`
178 pub words: WordsCompletionMode,
179 /// How many characters has to be in the completions query to automatically show the words-based completions.
180 /// Before that value, it's still possible to trigger the words-based completion manually with the corresponding editor command.
181 ///
182 /// Default: 3
183 pub words_min_length: usize,
184 /// Whether to fetch LSP completions or not.
185 ///
186 /// Default: true
187 pub lsp: bool,
188 /// When fetching LSP completions, determines how long to wait for a response of a particular server.
189 /// When set to 0, waits indefinitely.
190 ///
191 /// Default: 0
192 pub lsp_fetch_timeout_ms: u64,
193 /// Controls how LSP completions are inserted.
194 ///
195 /// Default: "replace_suffix"
196 pub lsp_insert_mode: LspInsertMode,
197}
198
199/// The settings for indent guides.
200#[derive(Debug, Clone, PartialEq)]
201pub struct IndentGuideSettings {
202 /// Whether to display indent guides in the editor.
203 ///
204 /// Default: true
205 pub enabled: bool,
206 /// The width of the indent guides in pixels, between 1 and 10.
207 ///
208 /// Default: 1
209 pub line_width: u32,
210 /// The width of the active indent guide in pixels, between 1 and 10.
211 ///
212 /// Default: 1
213 pub active_line_width: u32,
214 /// Determines how indent guides are colored.
215 ///
216 /// Default: Fixed
217 pub coloring: settings::IndentGuideColoring,
218 /// Determines how indent guide backgrounds are colored.
219 ///
220 /// Default: Disabled
221 pub background_coloring: settings::IndentGuideBackgroundColoring,
222}
223
224#[derive(Debug, Clone, PartialEq)]
225pub struct LanguageTaskSettings {
226 /// Extra task variables to set for a particular language.
227 pub variables: HashMap<String, String>,
228 pub enabled: bool,
229 /// Use LSP tasks over Zed language extension ones.
230 /// If no LSP tasks are returned due to error/timeout or regular execution,
231 /// Zed language extension tasks will be used instead.
232 ///
233 /// Other Zed tasks will still be shown:
234 /// * Zed task from either of the task config file
235 /// * Zed task from history (e.g. one-off task was spawned before)
236 pub prefer_lsp: bool,
237}
238
239/// Allows to enable/disable formatting with Prettier
240/// and configure default Prettier, used when no project-level Prettier installation is found.
241/// Prettier formatting is disabled by default.
242#[derive(Debug, Clone, PartialEq)]
243pub struct PrettierSettings {
244 /// Enables or disables formatting with Prettier for a given language.
245 pub allowed: bool,
246
247 /// Forces Prettier integration to use a specific parser name when formatting files with the language.
248 pub parser: Option<String>,
249
250 /// Forces Prettier integration to use specific plugins when formatting files with the language.
251 /// The default Prettier will be installed with these plugins.
252 pub plugins: HashSet<String>,
253
254 /// Default Prettier options, in the format as in package.json section for Prettier.
255 /// If project installs Prettier via its package.json, these options will be ignored.
256 pub options: HashMap<String, serde_json::Value>,
257}
258
259impl LanguageSettings {
260 /// A token representing the rest of the available language servers.
261 const REST_OF_LANGUAGE_SERVERS: &'static str = "...";
262
263 /// Returns the customized list of language servers from the list of
264 /// available language servers.
265 pub fn customized_language_servers(
266 &self,
267 available_language_servers: &[LanguageServerName],
268 ) -> Vec<LanguageServerName> {
269 Self::resolve_language_servers(&self.language_servers, available_language_servers)
270 }
271
272 pub(crate) fn resolve_language_servers(
273 configured_language_servers: &[String],
274 available_language_servers: &[LanguageServerName],
275 ) -> Vec<LanguageServerName> {
276 let (disabled_language_servers, enabled_language_servers): (
277 Vec<LanguageServerName>,
278 Vec<LanguageServerName>,
279 ) = configured_language_servers.iter().partition_map(
280 |language_server| match language_server.strip_prefix('!') {
281 Some(disabled) => Either::Left(LanguageServerName(disabled.to_string().into())),
282 None => Either::Right(LanguageServerName(language_server.clone().into())),
283 },
284 );
285
286 let rest = available_language_servers
287 .iter()
288 .filter(|&available_language_server| {
289 !disabled_language_servers.contains(available_language_server)
290 && !enabled_language_servers.contains(available_language_server)
291 })
292 .cloned()
293 .collect::<Vec<_>>();
294
295 enabled_language_servers
296 .into_iter()
297 .flat_map(|language_server| {
298 if language_server.0.as_ref() == Self::REST_OF_LANGUAGE_SERVERS {
299 rest.clone()
300 } else {
301 vec![language_server]
302 }
303 })
304 .collect::<Vec<_>>()
305 }
306}
307
308// The settings for inlay hints.
309#[derive(Copy, Clone, Debug, PartialEq, Eq)]
310pub struct InlayHintSettings {
311 /// Global switch to toggle hints on and off.
312 ///
313 /// Default: false
314 pub enabled: bool,
315 /// Global switch to toggle inline values on and off when debugging.
316 ///
317 /// Default: true
318 pub show_value_hints: bool,
319 /// Whether type hints should be shown.
320 ///
321 /// Default: true
322 pub show_type_hints: bool,
323 /// Whether parameter hints should be shown.
324 ///
325 /// Default: true
326 pub show_parameter_hints: bool,
327 /// Whether other hints should be shown.
328 ///
329 /// Default: true
330 pub show_other_hints: bool,
331 /// Whether to show a background for inlay hints.
332 ///
333 /// If set to `true`, the background will use the `hint.background` color
334 /// from the current theme.
335 ///
336 /// Default: false
337 pub show_background: bool,
338 /// Whether or not to debounce inlay hints updates after buffer edits.
339 ///
340 /// Set to 0 to disable debouncing.
341 ///
342 /// Default: 700
343 pub edit_debounce_ms: u64,
344 /// Whether or not to debounce inlay hints updates after buffer scrolls.
345 ///
346 /// Set to 0 to disable debouncing.
347 ///
348 /// Default: 50
349 pub scroll_debounce_ms: u64,
350 /// Toggles inlay hints (hides or shows) when the user presses the modifiers specified.
351 /// If only a subset of the modifiers specified is pressed, hints are not toggled.
352 /// If no modifiers are specified, this is equivalent to `None`.
353 ///
354 /// Default: None
355 pub toggle_on_modifiers_press: Option<Modifiers>,
356}
357
358impl InlayHintSettings {
359 /// Returns the kinds of inlay hints that are enabled based on the settings.
360 pub fn enabled_inlay_hint_kinds(&self) -> HashSet<Option<InlayHintKind>> {
361 let mut kinds = HashSet::default();
362 if self.show_type_hints {
363 kinds.insert(Some(InlayHintKind::Type));
364 }
365 if self.show_parameter_hints {
366 kinds.insert(Some(InlayHintKind::Parameter));
367 }
368 if self.show_other_hints {
369 kinds.insert(None);
370 }
371 kinds
372 }
373}
374
375/// The settings for edit predictions, such as [GitHub Copilot](https://github.com/features/copilot)
376/// or [Supermaven](https://supermaven.com).
377#[derive(Clone, Debug, Default)]
378pub struct EditPredictionSettings {
379 /// The provider that supplies edit predictions.
380 pub provider: settings::EditPredictionProvider,
381 /// Whether to use the experimental edit prediction context retrieval system.
382 pub use_context: bool,
383 /// A list of globs representing files that edit predictions should be disabled for.
384 /// This list adds to a pre-existing, sensible default set of globs.
385 /// Any additional ones you add are combined with them.
386 pub disabled_globs: Vec<DisabledGlob>,
387 /// Configures how edit predictions are displayed in the buffer.
388 pub mode: settings::EditPredictionsMode,
389 /// Settings specific to GitHub Copilot.
390 pub copilot: CopilotSettings,
391 /// Settings specific to Codestral.
392 pub codestral: CodestralSettings,
393 /// Whether edit predictions are enabled in the assistant panel.
394 /// This setting has no effect if globally disabled.
395 pub enabled_in_text_threads: bool,
396 pub examples_dir: Option<Arc<Path>>,
397 pub example_capture_rate: Option<u16>,
398}
399
400impl EditPredictionSettings {
401 /// Returns whether edit predictions are enabled for the given path.
402 pub fn enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
403 !self.disabled_globs.iter().any(|glob| {
404 if glob.is_absolute {
405 file.as_local()
406 .is_some_and(|local| glob.matcher.is_match(local.abs_path(cx)))
407 } else {
408 glob.matcher.is_match(file.path().as_std_path())
409 }
410 })
411 }
412}
413
414#[derive(Clone, Debug)]
415pub struct DisabledGlob {
416 matcher: GlobMatcher,
417 is_absolute: bool,
418}
419
420#[derive(Clone, Debug, Default)]
421pub struct CopilotSettings {
422 /// HTTP/HTTPS proxy to use for Copilot.
423 pub proxy: Option<String>,
424 /// Disable certificate verification for proxy (not recommended).
425 pub proxy_no_verify: Option<bool>,
426 /// Enterprise URI for Copilot.
427 pub enterprise_uri: Option<String>,
428}
429
430#[derive(Clone, Debug, Default)]
431pub struct CodestralSettings {
432 /// Model to use for completions.
433 pub model: Option<String>,
434 /// Maximum tokens to generate.
435 pub max_tokens: Option<u32>,
436 /// Custom API URL to use for Codestral.
437 pub api_url: Option<String>,
438}
439
440impl AllLanguageSettings {
441 /// Returns the [`LanguageSettings`] for the language with the specified name.
442 pub fn language<'a>(
443 &'a self,
444 location: Option<SettingsLocation<'a>>,
445 language_name: Option<&LanguageName>,
446 cx: &'a App,
447 ) -> Cow<'a, LanguageSettings> {
448 let settings = language_name
449 .and_then(|name| self.languages.get(name))
450 .unwrap_or(&self.defaults);
451
452 let editorconfig_properties = location.and_then(|location| {
453 cx.global::<SettingsStore>()
454 .editorconfig_store
455 .read(cx)
456 .properties(location.worktree_id, location.path)
457 });
458 if let Some(editorconfig_properties) = editorconfig_properties {
459 let mut settings = settings.clone();
460 merge_with_editorconfig(&mut settings, &editorconfig_properties);
461 Cow::Owned(settings)
462 } else {
463 Cow::Borrowed(settings)
464 }
465 }
466
467 /// Returns whether edit predictions are enabled for the given path.
468 pub fn edit_predictions_enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
469 self.edit_predictions.enabled_for_file(file, cx)
470 }
471
472 /// Returns whether edit predictions are enabled for the given language and path.
473 pub fn show_edit_predictions(&self, language: Option<&Arc<Language>>, cx: &App) -> bool {
474 self.language(None, language.map(|l| l.name()).as_ref(), cx)
475 .show_edit_predictions
476 }
477
478 /// Returns the edit predictions preview mode for the given language and path.
479 pub fn edit_predictions_mode(&self) -> EditPredictionsMode {
480 self.edit_predictions.mode
481 }
482}
483
484fn merge_with_editorconfig(settings: &mut LanguageSettings, cfg: &EditorconfigProperties) {
485 let preferred_line_length = cfg.get::<MaxLineLen>().ok().and_then(|v| match v {
486 MaxLineLen::Value(u) => Some(u as u32),
487 MaxLineLen::Off => None,
488 });
489 let tab_size = cfg.get::<IndentSize>().ok().and_then(|v| match v {
490 IndentSize::Value(u) => NonZeroU32::new(u as u32),
491 IndentSize::UseTabWidth => cfg.get::<TabWidth>().ok().and_then(|w| match w {
492 TabWidth::Value(u) => NonZeroU32::new(u as u32),
493 }),
494 });
495 let hard_tabs = cfg
496 .get::<IndentStyle>()
497 .map(|v| v.eq(&IndentStyle::Tabs))
498 .ok();
499 let ensure_final_newline_on_save = cfg
500 .get::<FinalNewline>()
501 .map(|v| match v {
502 FinalNewline::Value(b) => b,
503 })
504 .ok();
505 let remove_trailing_whitespace_on_save = cfg
506 .get::<TrimTrailingWs>()
507 .map(|v| match v {
508 TrimTrailingWs::Value(b) => b,
509 })
510 .ok();
511 fn merge<T>(target: &mut T, value: Option<T>) {
512 if let Some(value) = value {
513 *target = value;
514 }
515 }
516 merge(&mut settings.preferred_line_length, preferred_line_length);
517 merge(&mut settings.tab_size, tab_size);
518 merge(&mut settings.hard_tabs, hard_tabs);
519 merge(
520 &mut settings.remove_trailing_whitespace_on_save,
521 remove_trailing_whitespace_on_save,
522 );
523 merge(
524 &mut settings.ensure_final_newline_on_save,
525 ensure_final_newline_on_save,
526 );
527}
528
529impl settings::Settings for AllLanguageSettings {
530 fn from_settings(content: &settings::SettingsContent) -> Self {
531 let all_languages = &content.project.all_languages;
532
533 fn load_from_content(settings: LanguageSettingsContent) -> LanguageSettings {
534 let inlay_hints = settings.inlay_hints.unwrap();
535 let completions = settings.completions.unwrap();
536 let prettier = settings.prettier.unwrap();
537 let indent_guides = settings.indent_guides.unwrap();
538 let tasks = settings.tasks.unwrap();
539 let whitespace_map = settings.whitespace_map.unwrap();
540
541 LanguageSettings {
542 tab_size: settings.tab_size.unwrap(),
543 hard_tabs: settings.hard_tabs.unwrap(),
544 soft_wrap: settings.soft_wrap.unwrap(),
545 preferred_line_length: settings.preferred_line_length.unwrap(),
546 show_wrap_guides: settings.show_wrap_guides.unwrap(),
547 wrap_guides: settings.wrap_guides.unwrap(),
548 indent_guides: IndentGuideSettings {
549 enabled: indent_guides.enabled.unwrap(),
550 line_width: indent_guides.line_width.unwrap(),
551 active_line_width: indent_guides.active_line_width.unwrap(),
552 coloring: indent_guides.coloring.unwrap(),
553 background_coloring: indent_guides.background_coloring.unwrap(),
554 },
555 format_on_save: settings.format_on_save.unwrap(),
556 remove_trailing_whitespace_on_save: settings
557 .remove_trailing_whitespace_on_save
558 .unwrap(),
559 ensure_final_newline_on_save: settings.ensure_final_newline_on_save.unwrap(),
560 formatter: settings.formatter.unwrap(),
561 prettier: PrettierSettings {
562 allowed: prettier.allowed.unwrap(),
563 parser: prettier.parser.filter(|parser| !parser.is_empty()),
564 plugins: prettier.plugins.unwrap_or_default(),
565 options: prettier.options.unwrap_or_default(),
566 },
567 jsx_tag_auto_close: settings.jsx_tag_auto_close.unwrap().enabled.unwrap(),
568 enable_language_server: settings.enable_language_server.unwrap(),
569 language_servers: settings.language_servers.unwrap(),
570 allow_rewrap: settings.allow_rewrap.unwrap(),
571 show_edit_predictions: settings.show_edit_predictions.unwrap(),
572 edit_predictions_disabled_in: settings.edit_predictions_disabled_in.unwrap(),
573 show_whitespaces: settings.show_whitespaces.unwrap(),
574 whitespace_map: WhitespaceMap {
575 space: SharedString::new(whitespace_map.space.unwrap().to_string()),
576 tab: SharedString::new(whitespace_map.tab.unwrap().to_string()),
577 },
578 extend_comment_on_newline: settings.extend_comment_on_newline.unwrap(),
579 extend_list_on_newline: settings.extend_list_on_newline.unwrap(),
580 indent_list_on_tab: settings.indent_list_on_tab.unwrap(),
581 inlay_hints: InlayHintSettings {
582 enabled: inlay_hints.enabled.unwrap(),
583 show_value_hints: inlay_hints.show_value_hints.unwrap(),
584 show_type_hints: inlay_hints.show_type_hints.unwrap(),
585 show_parameter_hints: inlay_hints.show_parameter_hints.unwrap(),
586 show_other_hints: inlay_hints.show_other_hints.unwrap(),
587 show_background: inlay_hints.show_background.unwrap(),
588 edit_debounce_ms: inlay_hints.edit_debounce_ms.unwrap(),
589 scroll_debounce_ms: inlay_hints.scroll_debounce_ms.unwrap(),
590 toggle_on_modifiers_press: inlay_hints
591 .toggle_on_modifiers_press
592 .map(|m| m.into_gpui()),
593 },
594 use_autoclose: settings.use_autoclose.unwrap(),
595 use_auto_surround: settings.use_auto_surround.unwrap(),
596 use_on_type_format: settings.use_on_type_format.unwrap(),
597 auto_indent: settings.auto_indent.unwrap(),
598 auto_indent_on_paste: settings.auto_indent_on_paste.unwrap(),
599 always_treat_brackets_as_autoclosed: settings
600 .always_treat_brackets_as_autoclosed
601 .unwrap(),
602 code_actions_on_format: settings.code_actions_on_format.unwrap(),
603 linked_edits: settings.linked_edits.unwrap(),
604 tasks: LanguageTaskSettings {
605 variables: tasks.variables.unwrap_or_default(),
606 enabled: tasks.enabled.unwrap(),
607 prefer_lsp: tasks.prefer_lsp.unwrap(),
608 },
609 show_completions_on_input: settings.show_completions_on_input.unwrap(),
610 show_completion_documentation: settings.show_completion_documentation.unwrap(),
611 colorize_brackets: settings.colorize_brackets.unwrap(),
612 completions: CompletionSettings {
613 words: completions.words.unwrap(),
614 words_min_length: completions.words_min_length.unwrap() as usize,
615 lsp: completions.lsp.unwrap(),
616 lsp_fetch_timeout_ms: completions.lsp_fetch_timeout_ms.unwrap(),
617 lsp_insert_mode: completions.lsp_insert_mode.unwrap(),
618 },
619 debuggers: settings.debuggers.unwrap(),
620 word_diff_enabled: settings.word_diff_enabled.unwrap(),
621 }
622 }
623
624 let default_language_settings = load_from_content(all_languages.defaults.clone());
625
626 let mut languages = HashMap::default();
627 for (language_name, settings) in &all_languages.languages.0 {
628 let mut language_settings = all_languages.defaults.clone();
629 settings::merge_from::MergeFrom::merge_from(&mut language_settings, settings);
630 languages.insert(
631 LanguageName(language_name.clone().into()),
632 load_from_content(language_settings),
633 );
634 }
635
636 let edit_prediction_provider = all_languages
637 .features
638 .as_ref()
639 .and_then(|f| f.edit_prediction_provider);
640 let use_edit_prediction_context = all_languages
641 .features
642 .as_ref()
643 .and_then(|f| f.experimental_edit_prediction_context_retrieval)
644 .unwrap_or_default();
645
646 let edit_predictions = all_languages.edit_predictions.clone().unwrap();
647 let edit_predictions_mode = edit_predictions.mode.unwrap();
648
649 let disabled_globs: HashSet<&String> = edit_predictions
650 .disabled_globs
651 .as_ref()
652 .unwrap()
653 .iter()
654 .collect();
655
656 let copilot = edit_predictions.copilot.unwrap();
657 let copilot_settings = CopilotSettings {
658 proxy: copilot.proxy,
659 proxy_no_verify: copilot.proxy_no_verify,
660 enterprise_uri: copilot.enterprise_uri,
661 };
662
663 let codestral = edit_predictions.codestral.unwrap();
664 let codestral_settings = CodestralSettings {
665 model: codestral.model,
666 max_tokens: codestral.max_tokens,
667 api_url: codestral.api_url,
668 };
669
670 let enabled_in_text_threads = edit_predictions.enabled_in_text_threads.unwrap();
671
672 let mut file_types: FxHashMap<Arc<str>, (GlobSet, Vec<String>)> = FxHashMap::default();
673
674 for (language, patterns) in all_languages.file_types.iter().flatten() {
675 let mut builder = GlobSetBuilder::new();
676
677 for pattern in &patterns.0 {
678 builder.add(Glob::new(pattern).unwrap());
679 }
680
681 file_types.insert(
682 language.clone(),
683 (builder.build().unwrap(), patterns.0.clone()),
684 );
685 }
686
687 Self {
688 edit_predictions: EditPredictionSettings {
689 provider: if let Some(provider) = edit_prediction_provider {
690 provider
691 } else {
692 EditPredictionProvider::None
693 },
694 use_context: use_edit_prediction_context,
695 disabled_globs: disabled_globs
696 .iter()
697 .filter_map(|g| {
698 let expanded_g = shellexpand::tilde(g).into_owned();
699 Some(DisabledGlob {
700 matcher: globset::Glob::new(&expanded_g).ok()?.compile_matcher(),
701 is_absolute: Path::new(&expanded_g).is_absolute(),
702 })
703 })
704 .collect(),
705 mode: edit_predictions_mode,
706 copilot: copilot_settings,
707 codestral: codestral_settings,
708 enabled_in_text_threads,
709 examples_dir: edit_predictions.examples_dir,
710 example_capture_rate: edit_predictions.example_capture_rate,
711 },
712 defaults: default_language_settings,
713 languages,
714 file_types,
715 }
716 }
717}
718
719#[derive(Default, Debug, Clone, PartialEq, Eq)]
720pub struct JsxTagAutoCloseSettings {
721 /// Enables or disables auto-closing of JSX tags.
722 pub enabled: bool,
723}
724
725#[cfg(test)]
726mod tests {
727 use super::*;
728 use gpui::TestAppContext;
729 use util::rel_path::rel_path;
730
731 #[gpui::test]
732 fn test_edit_predictions_enabled_for_file(cx: &mut TestAppContext) {
733 use crate::TestFile;
734 use std::path::PathBuf;
735
736 let cx = cx.app.borrow_mut();
737
738 let build_settings = |globs: &[&str]| -> EditPredictionSettings {
739 EditPredictionSettings {
740 disabled_globs: globs
741 .iter()
742 .map(|glob_str| {
743 #[cfg(windows)]
744 let glob_str = {
745 let mut g = String::new();
746
747 if glob_str.starts_with('/') {
748 g.push_str("C:");
749 }
750
751 g.push_str(&glob_str.replace('/', "\\"));
752 g
753 };
754 #[cfg(windows)]
755 let glob_str = glob_str.as_str();
756 let expanded_glob_str = shellexpand::tilde(glob_str).into_owned();
757 DisabledGlob {
758 matcher: globset::Glob::new(&expanded_glob_str)
759 .unwrap()
760 .compile_matcher(),
761 is_absolute: Path::new(&expanded_glob_str).is_absolute(),
762 }
763 })
764 .collect(),
765 ..Default::default()
766 }
767 };
768
769 const WORKTREE_NAME: &str = "project";
770 let make_test_file = |segments: &[&str]| -> Arc<dyn File> {
771 let path = segments.join("/");
772 let path = rel_path(&path);
773
774 Arc::new(TestFile {
775 path: path.into(),
776 root_name: WORKTREE_NAME.to_string(),
777 local_root: Some(PathBuf::from(if cfg!(windows) {
778 "C:\\absolute\\"
779 } else {
780 "/absolute/"
781 })),
782 })
783 };
784
785 let test_file = make_test_file(&["src", "test", "file.rs"]);
786
787 // Test relative globs
788 let settings = build_settings(&["*.rs"]);
789 assert!(!settings.enabled_for_file(&test_file, &cx));
790 let settings = build_settings(&["*.txt"]);
791 assert!(settings.enabled_for_file(&test_file, &cx));
792
793 // Test absolute globs
794 let settings = build_settings(&["/absolute/**/*.rs"]);
795 assert!(!settings.enabled_for_file(&test_file, &cx));
796 let settings = build_settings(&["/other/**/*.rs"]);
797 assert!(settings.enabled_for_file(&test_file, &cx));
798
799 // Test exact path match relative
800 let settings = build_settings(&["src/test/file.rs"]);
801 assert!(!settings.enabled_for_file(&test_file, &cx));
802 let settings = build_settings(&["src/test/otherfile.rs"]);
803 assert!(settings.enabled_for_file(&test_file, &cx));
804
805 // Test exact path match absolute
806 let settings = build_settings(&[&format!("/absolute/{}/src/test/file.rs", WORKTREE_NAME)]);
807 assert!(!settings.enabled_for_file(&test_file, &cx));
808 let settings = build_settings(&["/other/test/otherfile.rs"]);
809 assert!(settings.enabled_for_file(&test_file, &cx));
810
811 // Test * glob
812 let settings = build_settings(&["*"]);
813 assert!(!settings.enabled_for_file(&test_file, &cx));
814 let settings = build_settings(&["*.txt"]);
815 assert!(settings.enabled_for_file(&test_file, &cx));
816
817 // Test **/* glob
818 let settings = build_settings(&["**/*"]);
819 assert!(!settings.enabled_for_file(&test_file, &cx));
820 let settings = build_settings(&["other/**/*"]);
821 assert!(settings.enabled_for_file(&test_file, &cx));
822
823 // Test directory/** glob
824 let settings = build_settings(&["src/**"]);
825 assert!(!settings.enabled_for_file(&test_file, &cx));
826
827 let test_file_root: Arc<dyn File> = Arc::new(TestFile {
828 path: rel_path("file.rs").into(),
829 root_name: WORKTREE_NAME.to_string(),
830 local_root: Some(PathBuf::from("/absolute/")),
831 });
832 assert!(settings.enabled_for_file(&test_file_root, &cx));
833
834 let settings = build_settings(&["other/**"]);
835 assert!(settings.enabled_for_file(&test_file, &cx));
836
837 // Test **/directory/* glob
838 let settings = build_settings(&["**/test/*"]);
839 assert!(!settings.enabled_for_file(&test_file, &cx));
840 let settings = build_settings(&["**/other/*"]);
841 assert!(settings.enabled_for_file(&test_file, &cx));
842
843 // Test multiple globs
844 let settings = build_settings(&["*.rs", "*.txt", "src/**"]);
845 assert!(!settings.enabled_for_file(&test_file, &cx));
846 let settings = build_settings(&["*.txt", "*.md", "other/**"]);
847 assert!(settings.enabled_for_file(&test_file, &cx));
848
849 // Test dot files
850 let dot_file = make_test_file(&[".config", "settings.json"]);
851 let settings = build_settings(&[".*/**"]);
852 assert!(!settings.enabled_for_file(&dot_file, &cx));
853
854 let dot_env_file = make_test_file(&[".env"]);
855 let settings = build_settings(&[".env"]);
856 assert!(!settings.enabled_for_file(&dot_env_file, &cx));
857
858 // Test tilde expansion
859 let home = shellexpand::tilde("~").into_owned();
860 let home_file = Arc::new(TestFile {
861 path: rel_path("test.rs").into(),
862 root_name: "the-dir".to_string(),
863 local_root: Some(PathBuf::from(home)),
864 }) as Arc<dyn File>;
865 let settings = build_settings(&["~/the-dir/test.rs"]);
866 assert!(!settings.enabled_for_file(&home_file, &cx));
867 }
868
869 #[test]
870 fn test_resolve_language_servers() {
871 fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
872 names
873 .iter()
874 .copied()
875 .map(|name| LanguageServerName(name.to_string().into()))
876 .collect::<Vec<_>>()
877 }
878
879 let available_language_servers = language_server_names(&[
880 "typescript-language-server",
881 "biome",
882 "deno",
883 "eslint",
884 "tailwind",
885 ]);
886
887 // A value of just `["..."]` is the same as taking all of the available language servers.
888 assert_eq!(
889 LanguageSettings::resolve_language_servers(
890 &[LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()],
891 &available_language_servers,
892 ),
893 available_language_servers
894 );
895
896 // Referencing one of the available language servers will change its order.
897 assert_eq!(
898 LanguageSettings::resolve_language_servers(
899 &[
900 "biome".into(),
901 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into(),
902 "deno".into()
903 ],
904 &available_language_servers
905 ),
906 language_server_names(&[
907 "biome",
908 "typescript-language-server",
909 "eslint",
910 "tailwind",
911 "deno",
912 ])
913 );
914
915 // Negating an available language server removes it from the list.
916 assert_eq!(
917 LanguageSettings::resolve_language_servers(
918 &[
919 "deno".into(),
920 "!typescript-language-server".into(),
921 "!biome".into(),
922 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
923 ],
924 &available_language_servers
925 ),
926 language_server_names(&["deno", "eslint", "tailwind"])
927 );
928
929 // Adding a language server not in the list of available language servers adds it to the list.
930 assert_eq!(
931 LanguageSettings::resolve_language_servers(
932 &[
933 "my-cool-language-server".into(),
934 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
935 ],
936 &available_language_servers
937 ),
938 language_server_names(&[
939 "my-cool-language-server",
940 "typescript-language-server",
941 "biome",
942 "deno",
943 "eslint",
944 "tailwind",
945 ])
946 );
947 }
948}