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