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_properties(location.worktree_id, location.path)
455 });
456 if let Some(editorconfig_properties) = editorconfig_properties {
457 let mut settings = settings.clone();
458 merge_with_editorconfig(&mut settings, &editorconfig_properties);
459 Cow::Owned(settings)
460 } else {
461 Cow::Borrowed(settings)
462 }
463 }
464
465 /// Returns whether edit predictions are enabled for the given path.
466 pub fn edit_predictions_enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
467 self.edit_predictions.enabled_for_file(file, cx)
468 }
469
470 /// Returns whether edit predictions are enabled for the given language and path.
471 pub fn show_edit_predictions(&self, language: Option<&Arc<Language>>, cx: &App) -> bool {
472 self.language(None, language.map(|l| l.name()).as_ref(), cx)
473 .show_edit_predictions
474 }
475
476 /// Returns the edit predictions preview mode for the given language and path.
477 pub fn edit_predictions_mode(&self) -> EditPredictionsMode {
478 self.edit_predictions.mode
479 }
480}
481
482fn merge_with_editorconfig(settings: &mut LanguageSettings, cfg: &EditorconfigProperties) {
483 let preferred_line_length = cfg.get::<MaxLineLen>().ok().and_then(|v| match v {
484 MaxLineLen::Value(u) => Some(u as u32),
485 MaxLineLen::Off => None,
486 });
487 let tab_size = cfg.get::<IndentSize>().ok().and_then(|v| match v {
488 IndentSize::Value(u) => NonZeroU32::new(u as u32),
489 IndentSize::UseTabWidth => cfg.get::<TabWidth>().ok().and_then(|w| match w {
490 TabWidth::Value(u) => NonZeroU32::new(u as u32),
491 }),
492 });
493 let hard_tabs = cfg
494 .get::<IndentStyle>()
495 .map(|v| v.eq(&IndentStyle::Tabs))
496 .ok();
497 let ensure_final_newline_on_save = cfg
498 .get::<FinalNewline>()
499 .map(|v| match v {
500 FinalNewline::Value(b) => b,
501 })
502 .ok();
503 let remove_trailing_whitespace_on_save = cfg
504 .get::<TrimTrailingWs>()
505 .map(|v| match v {
506 TrimTrailingWs::Value(b) => b,
507 })
508 .ok();
509 fn merge<T>(target: &mut T, value: Option<T>) {
510 if let Some(value) = value {
511 *target = value;
512 }
513 }
514 merge(&mut settings.preferred_line_length, preferred_line_length);
515 merge(&mut settings.tab_size, tab_size);
516 merge(&mut settings.hard_tabs, hard_tabs);
517 merge(
518 &mut settings.remove_trailing_whitespace_on_save,
519 remove_trailing_whitespace_on_save,
520 );
521 merge(
522 &mut settings.ensure_final_newline_on_save,
523 ensure_final_newline_on_save,
524 );
525}
526
527impl settings::Settings for AllLanguageSettings {
528 fn from_settings(content: &settings::SettingsContent) -> Self {
529 let all_languages = &content.project.all_languages;
530
531 fn load_from_content(settings: LanguageSettingsContent) -> LanguageSettings {
532 let inlay_hints = settings.inlay_hints.unwrap();
533 let completions = settings.completions.unwrap();
534 let prettier = settings.prettier.unwrap();
535 let indent_guides = settings.indent_guides.unwrap();
536 let tasks = settings.tasks.unwrap();
537 let whitespace_map = settings.whitespace_map.unwrap();
538
539 LanguageSettings {
540 tab_size: settings.tab_size.unwrap(),
541 hard_tabs: settings.hard_tabs.unwrap(),
542 soft_wrap: settings.soft_wrap.unwrap(),
543 preferred_line_length: settings.preferred_line_length.unwrap(),
544 show_wrap_guides: settings.show_wrap_guides.unwrap(),
545 wrap_guides: settings.wrap_guides.unwrap(),
546 indent_guides: IndentGuideSettings {
547 enabled: indent_guides.enabled.unwrap(),
548 line_width: indent_guides.line_width.unwrap(),
549 active_line_width: indent_guides.active_line_width.unwrap(),
550 coloring: indent_guides.coloring.unwrap(),
551 background_coloring: indent_guides.background_coloring.unwrap(),
552 },
553 format_on_save: settings.format_on_save.unwrap(),
554 remove_trailing_whitespace_on_save: settings
555 .remove_trailing_whitespace_on_save
556 .unwrap(),
557 ensure_final_newline_on_save: settings.ensure_final_newline_on_save.unwrap(),
558 formatter: settings.formatter.unwrap(),
559 prettier: PrettierSettings {
560 allowed: prettier.allowed.unwrap(),
561 parser: prettier.parser.filter(|parser| !parser.is_empty()),
562 plugins: prettier.plugins.unwrap_or_default(),
563 options: prettier.options.unwrap_or_default(),
564 },
565 jsx_tag_auto_close: settings.jsx_tag_auto_close.unwrap().enabled.unwrap(),
566 enable_language_server: settings.enable_language_server.unwrap(),
567 language_servers: settings.language_servers.unwrap(),
568 allow_rewrap: settings.allow_rewrap.unwrap(),
569 show_edit_predictions: settings.show_edit_predictions.unwrap(),
570 edit_predictions_disabled_in: settings.edit_predictions_disabled_in.unwrap(),
571 show_whitespaces: settings.show_whitespaces.unwrap(),
572 whitespace_map: WhitespaceMap {
573 space: SharedString::new(whitespace_map.space.unwrap().to_string()),
574 tab: SharedString::new(whitespace_map.tab.unwrap().to_string()),
575 },
576 extend_comment_on_newline: settings.extend_comment_on_newline.unwrap(),
577 extend_list_on_newline: settings.extend_list_on_newline.unwrap(),
578 indent_list_on_tab: settings.indent_list_on_tab.unwrap(),
579 inlay_hints: InlayHintSettings {
580 enabled: inlay_hints.enabled.unwrap(),
581 show_value_hints: inlay_hints.show_value_hints.unwrap(),
582 show_type_hints: inlay_hints.show_type_hints.unwrap(),
583 show_parameter_hints: inlay_hints.show_parameter_hints.unwrap(),
584 show_other_hints: inlay_hints.show_other_hints.unwrap(),
585 show_background: inlay_hints.show_background.unwrap(),
586 edit_debounce_ms: inlay_hints.edit_debounce_ms.unwrap(),
587 scroll_debounce_ms: inlay_hints.scroll_debounce_ms.unwrap(),
588 toggle_on_modifiers_press: inlay_hints
589 .toggle_on_modifiers_press
590 .map(|m| m.into_gpui()),
591 },
592 use_autoclose: settings.use_autoclose.unwrap(),
593 use_auto_surround: settings.use_auto_surround.unwrap(),
594 use_on_type_format: settings.use_on_type_format.unwrap(),
595 auto_indent: settings.auto_indent.unwrap(),
596 auto_indent_on_paste: settings.auto_indent_on_paste.unwrap(),
597 always_treat_brackets_as_autoclosed: settings
598 .always_treat_brackets_as_autoclosed
599 .unwrap(),
600 code_actions_on_format: settings.code_actions_on_format.unwrap(),
601 linked_edits: settings.linked_edits.unwrap(),
602 tasks: LanguageTaskSettings {
603 variables: tasks.variables.unwrap_or_default(),
604 enabled: tasks.enabled.unwrap(),
605 prefer_lsp: tasks.prefer_lsp.unwrap(),
606 },
607 show_completions_on_input: settings.show_completions_on_input.unwrap(),
608 show_completion_documentation: settings.show_completion_documentation.unwrap(),
609 colorize_brackets: settings.colorize_brackets.unwrap(),
610 completions: CompletionSettings {
611 words: completions.words.unwrap(),
612 words_min_length: completions.words_min_length.unwrap() as usize,
613 lsp: completions.lsp.unwrap(),
614 lsp_fetch_timeout_ms: completions.lsp_fetch_timeout_ms.unwrap(),
615 lsp_insert_mode: completions.lsp_insert_mode.unwrap(),
616 },
617 debuggers: settings.debuggers.unwrap(),
618 word_diff_enabled: settings.word_diff_enabled.unwrap(),
619 }
620 }
621
622 let default_language_settings = load_from_content(all_languages.defaults.clone());
623
624 let mut languages = HashMap::default();
625 for (language_name, settings) in &all_languages.languages.0 {
626 let mut language_settings = all_languages.defaults.clone();
627 settings::merge_from::MergeFrom::merge_from(&mut language_settings, settings);
628 languages.insert(
629 LanguageName(language_name.clone().into()),
630 load_from_content(language_settings),
631 );
632 }
633
634 let edit_prediction_provider = all_languages
635 .features
636 .as_ref()
637 .and_then(|f| f.edit_prediction_provider);
638 let use_edit_prediction_context = all_languages
639 .features
640 .as_ref()
641 .and_then(|f| f.experimental_edit_prediction_context_retrieval)
642 .unwrap_or_default();
643
644 let edit_predictions = all_languages.edit_predictions.clone().unwrap();
645 let edit_predictions_mode = edit_predictions.mode.unwrap();
646
647 let disabled_globs: HashSet<&String> = edit_predictions
648 .disabled_globs
649 .as_ref()
650 .unwrap()
651 .iter()
652 .collect();
653
654 let copilot = edit_predictions.copilot.unwrap();
655 let copilot_settings = CopilotSettings {
656 proxy: copilot.proxy,
657 proxy_no_verify: copilot.proxy_no_verify,
658 enterprise_uri: copilot.enterprise_uri,
659 };
660
661 let codestral = edit_predictions.codestral.unwrap();
662 let codestral_settings = CodestralSettings {
663 model: codestral.model,
664 max_tokens: codestral.max_tokens,
665 api_url: codestral.api_url,
666 };
667
668 let enabled_in_text_threads = edit_predictions.enabled_in_text_threads.unwrap();
669
670 let mut file_types: FxHashMap<Arc<str>, (GlobSet, Vec<String>)> = FxHashMap::default();
671
672 for (language, patterns) in all_languages.file_types.iter().flatten() {
673 let mut builder = GlobSetBuilder::new();
674
675 for pattern in &patterns.0 {
676 builder.add(Glob::new(pattern).unwrap());
677 }
678
679 file_types.insert(
680 language.clone(),
681 (builder.build().unwrap(), patterns.0.clone()),
682 );
683 }
684
685 Self {
686 edit_predictions: EditPredictionSettings {
687 provider: if let Some(provider) = edit_prediction_provider {
688 provider
689 } else {
690 EditPredictionProvider::None
691 },
692 use_context: use_edit_prediction_context,
693 disabled_globs: disabled_globs
694 .iter()
695 .filter_map(|g| {
696 let expanded_g = shellexpand::tilde(g).into_owned();
697 Some(DisabledGlob {
698 matcher: globset::Glob::new(&expanded_g).ok()?.compile_matcher(),
699 is_absolute: Path::new(&expanded_g).is_absolute(),
700 })
701 })
702 .collect(),
703 mode: edit_predictions_mode,
704 copilot: copilot_settings,
705 codestral: codestral_settings,
706 enabled_in_text_threads,
707 examples_dir: edit_predictions.examples_dir,
708 example_capture_rate: edit_predictions.example_capture_rate,
709 },
710 defaults: default_language_settings,
711 languages,
712 file_types,
713 }
714 }
715}
716
717#[derive(Default, Debug, Clone, PartialEq, Eq)]
718pub struct JsxTagAutoCloseSettings {
719 /// Enables or disables auto-closing of JSX tags.
720 pub enabled: bool,
721}
722
723#[cfg(test)]
724mod tests {
725 use super::*;
726 use gpui::TestAppContext;
727 use util::rel_path::rel_path;
728
729 #[gpui::test]
730 fn test_edit_predictions_enabled_for_file(cx: &mut TestAppContext) {
731 use crate::TestFile;
732 use std::path::PathBuf;
733
734 let cx = cx.app.borrow_mut();
735
736 let build_settings = |globs: &[&str]| -> EditPredictionSettings {
737 EditPredictionSettings {
738 disabled_globs: globs
739 .iter()
740 .map(|glob_str| {
741 #[cfg(windows)]
742 let glob_str = {
743 let mut g = String::new();
744
745 if glob_str.starts_with('/') {
746 g.push_str("C:");
747 }
748
749 g.push_str(&glob_str.replace('/', "\\"));
750 g
751 };
752 #[cfg(windows)]
753 let glob_str = glob_str.as_str();
754 let expanded_glob_str = shellexpand::tilde(glob_str).into_owned();
755 DisabledGlob {
756 matcher: globset::Glob::new(&expanded_glob_str)
757 .unwrap()
758 .compile_matcher(),
759 is_absolute: Path::new(&expanded_glob_str).is_absolute(),
760 }
761 })
762 .collect(),
763 ..Default::default()
764 }
765 };
766
767 const WORKTREE_NAME: &str = "project";
768 let make_test_file = |segments: &[&str]| -> Arc<dyn File> {
769 let path = segments.join("/");
770 let path = rel_path(&path);
771
772 Arc::new(TestFile {
773 path: path.into(),
774 root_name: WORKTREE_NAME.to_string(),
775 local_root: Some(PathBuf::from(if cfg!(windows) {
776 "C:\\absolute\\"
777 } else {
778 "/absolute/"
779 })),
780 })
781 };
782
783 let test_file = make_test_file(&["src", "test", "file.rs"]);
784
785 // Test relative globs
786 let settings = build_settings(&["*.rs"]);
787 assert!(!settings.enabled_for_file(&test_file, &cx));
788 let settings = build_settings(&["*.txt"]);
789 assert!(settings.enabled_for_file(&test_file, &cx));
790
791 // Test absolute globs
792 let settings = build_settings(&["/absolute/**/*.rs"]);
793 assert!(!settings.enabled_for_file(&test_file, &cx));
794 let settings = build_settings(&["/other/**/*.rs"]);
795 assert!(settings.enabled_for_file(&test_file, &cx));
796
797 // Test exact path match relative
798 let settings = build_settings(&["src/test/file.rs"]);
799 assert!(!settings.enabled_for_file(&test_file, &cx));
800 let settings = build_settings(&["src/test/otherfile.rs"]);
801 assert!(settings.enabled_for_file(&test_file, &cx));
802
803 // Test exact path match absolute
804 let settings = build_settings(&[&format!("/absolute/{}/src/test/file.rs", WORKTREE_NAME)]);
805 assert!(!settings.enabled_for_file(&test_file, &cx));
806 let settings = build_settings(&["/other/test/otherfile.rs"]);
807 assert!(settings.enabled_for_file(&test_file, &cx));
808
809 // Test * glob
810 let settings = build_settings(&["*"]);
811 assert!(!settings.enabled_for_file(&test_file, &cx));
812 let settings = build_settings(&["*.txt"]);
813 assert!(settings.enabled_for_file(&test_file, &cx));
814
815 // Test **/* glob
816 let settings = build_settings(&["**/*"]);
817 assert!(!settings.enabled_for_file(&test_file, &cx));
818 let settings = build_settings(&["other/**/*"]);
819 assert!(settings.enabled_for_file(&test_file, &cx));
820
821 // Test directory/** glob
822 let settings = build_settings(&["src/**"]);
823 assert!(!settings.enabled_for_file(&test_file, &cx));
824
825 let test_file_root: Arc<dyn File> = Arc::new(TestFile {
826 path: rel_path("file.rs").into(),
827 root_name: WORKTREE_NAME.to_string(),
828 local_root: Some(PathBuf::from("/absolute/")),
829 });
830 assert!(settings.enabled_for_file(&test_file_root, &cx));
831
832 let settings = build_settings(&["other/**"]);
833 assert!(settings.enabled_for_file(&test_file, &cx));
834
835 // Test **/directory/* glob
836 let settings = build_settings(&["**/test/*"]);
837 assert!(!settings.enabled_for_file(&test_file, &cx));
838 let settings = build_settings(&["**/other/*"]);
839 assert!(settings.enabled_for_file(&test_file, &cx));
840
841 // Test multiple globs
842 let settings = build_settings(&["*.rs", "*.txt", "src/**"]);
843 assert!(!settings.enabled_for_file(&test_file, &cx));
844 let settings = build_settings(&["*.txt", "*.md", "other/**"]);
845 assert!(settings.enabled_for_file(&test_file, &cx));
846
847 // Test dot files
848 let dot_file = make_test_file(&[".config", "settings.json"]);
849 let settings = build_settings(&[".*/**"]);
850 assert!(!settings.enabled_for_file(&dot_file, &cx));
851
852 let dot_env_file = make_test_file(&[".env"]);
853 let settings = build_settings(&[".env"]);
854 assert!(!settings.enabled_for_file(&dot_env_file, &cx));
855
856 // Test tilde expansion
857 let home = shellexpand::tilde("~").into_owned();
858 let home_file = Arc::new(TestFile {
859 path: rel_path("test.rs").into(),
860 root_name: "the-dir".to_string(),
861 local_root: Some(PathBuf::from(home)),
862 }) as Arc<dyn File>;
863 let settings = build_settings(&["~/the-dir/test.rs"]);
864 assert!(!settings.enabled_for_file(&home_file, &cx));
865 }
866
867 #[test]
868 fn test_resolve_language_servers() {
869 fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
870 names
871 .iter()
872 .copied()
873 .map(|name| LanguageServerName(name.to_string().into()))
874 .collect::<Vec<_>>()
875 }
876
877 let available_language_servers = language_server_names(&[
878 "typescript-language-server",
879 "biome",
880 "deno",
881 "eslint",
882 "tailwind",
883 ]);
884
885 // A value of just `["..."]` is the same as taking all of the available language servers.
886 assert_eq!(
887 LanguageSettings::resolve_language_servers(
888 &[LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()],
889 &available_language_servers,
890 ),
891 available_language_servers
892 );
893
894 // Referencing one of the available language servers will change its order.
895 assert_eq!(
896 LanguageSettings::resolve_language_servers(
897 &[
898 "biome".into(),
899 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into(),
900 "deno".into()
901 ],
902 &available_language_servers
903 ),
904 language_server_names(&[
905 "biome",
906 "typescript-language-server",
907 "eslint",
908 "tailwind",
909 "deno",
910 ])
911 );
912
913 // Negating an available language server removes it from the list.
914 assert_eq!(
915 LanguageSettings::resolve_language_servers(
916 &[
917 "deno".into(),
918 "!typescript-language-server".into(),
919 "!biome".into(),
920 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
921 ],
922 &available_language_servers
923 ),
924 language_server_names(&["deno", "eslint", "tailwind"])
925 );
926
927 // Adding a language server not in the list of available language servers adds it to the list.
928 assert_eq!(
929 LanguageSettings::resolve_language_servers(
930 &[
931 "my-cool-language-server".into(),
932 LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
933 ],
934 &available_language_servers
935 ),
936 language_server_names(&[
937 "my-cool-language-server",
938 "typescript-language-server",
939 "biome",
940 "deno",
941 "eslint",
942 "tailwind",
943 ])
944 );
945 }
946}