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