language_settings.rs

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