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