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