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