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