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, 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    /// Whether edit predictions are enabled in the assistant panel.
 381    /// This setting has no effect if globally disabled.
 382    pub enabled_in_text_threads: bool,
 383}
 384
 385impl EditPredictionSettings {
 386    /// Returns whether edit predictions are enabled for the given path.
 387    pub fn enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
 388        !self.disabled_globs.iter().any(|glob| {
 389            if glob.is_absolute {
 390                file.as_local()
 391                    .is_some_and(|local| glob.matcher.is_match(local.abs_path(cx)))
 392            } else {
 393                glob.matcher.is_match(file.path().as_std_path())
 394            }
 395        })
 396    }
 397}
 398
 399#[derive(Clone, Debug)]
 400pub struct DisabledGlob {
 401    matcher: GlobMatcher,
 402    is_absolute: bool,
 403}
 404
 405#[derive(Clone, Debug, Default)]
 406pub struct CopilotSettings {
 407    /// HTTP/HTTPS proxy to use for Copilot.
 408    pub proxy: Option<String>,
 409    /// Disable certificate verification for proxy (not recommended).
 410    pub proxy_no_verify: Option<bool>,
 411    /// Enterprise URI for Copilot.
 412    pub enterprise_uri: Option<String>,
 413}
 414
 415impl AllLanguageSettings {
 416    /// Returns the [`LanguageSettings`] for the language with the specified name.
 417    pub fn language<'a>(
 418        &'a self,
 419        location: Option<SettingsLocation<'a>>,
 420        language_name: Option<&LanguageName>,
 421        cx: &'a App,
 422    ) -> Cow<'a, LanguageSettings> {
 423        let settings = language_name
 424            .and_then(|name| self.languages.get(name))
 425            .unwrap_or(&self.defaults);
 426
 427        let editorconfig_properties = location.and_then(|location| {
 428            cx.global::<SettingsStore>()
 429                .editorconfig_properties(location.worktree_id, location.path)
 430        });
 431        if let Some(editorconfig_properties) = editorconfig_properties {
 432            let mut settings = settings.clone();
 433            merge_with_editorconfig(&mut settings, &editorconfig_properties);
 434            Cow::Owned(settings)
 435        } else {
 436            Cow::Borrowed(settings)
 437        }
 438    }
 439
 440    /// Returns whether edit predictions are enabled for the given path.
 441    pub fn edit_predictions_enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
 442        self.edit_predictions.enabled_for_file(file, cx)
 443    }
 444
 445    /// Returns whether edit predictions are enabled for the given language and path.
 446    pub fn show_edit_predictions(&self, language: Option<&Arc<Language>>, cx: &App) -> bool {
 447        self.language(None, language.map(|l| l.name()).as_ref(), cx)
 448            .show_edit_predictions
 449    }
 450
 451    /// Returns the edit predictions preview mode for the given language and path.
 452    pub fn edit_predictions_mode(&self) -> EditPredictionsMode {
 453        self.edit_predictions.mode
 454    }
 455}
 456
 457fn merge_with_editorconfig(settings: &mut LanguageSettings, cfg: &EditorconfigProperties) {
 458    let preferred_line_length = cfg.get::<MaxLineLen>().ok().and_then(|v| match v {
 459        MaxLineLen::Value(u) => Some(u as u32),
 460        MaxLineLen::Off => None,
 461    });
 462    let tab_size = cfg.get::<IndentSize>().ok().and_then(|v| match v {
 463        IndentSize::Value(u) => NonZeroU32::new(u as u32),
 464        IndentSize::UseTabWidth => cfg.get::<TabWidth>().ok().and_then(|w| match w {
 465            TabWidth::Value(u) => NonZeroU32::new(u as u32),
 466        }),
 467    });
 468    let hard_tabs = cfg
 469        .get::<IndentStyle>()
 470        .map(|v| v.eq(&IndentStyle::Tabs))
 471        .ok();
 472    let ensure_final_newline_on_save = cfg
 473        .get::<FinalNewline>()
 474        .map(|v| match v {
 475            FinalNewline::Value(b) => b,
 476        })
 477        .ok();
 478    let remove_trailing_whitespace_on_save = cfg
 479        .get::<TrimTrailingWs>()
 480        .map(|v| match v {
 481            TrimTrailingWs::Value(b) => b,
 482        })
 483        .ok();
 484    fn merge<T>(target: &mut T, value: Option<T>) {
 485        if let Some(value) = value {
 486            *target = value;
 487        }
 488    }
 489    merge(&mut settings.preferred_line_length, preferred_line_length);
 490    merge(&mut settings.tab_size, tab_size);
 491    merge(&mut settings.hard_tabs, hard_tabs);
 492    merge(
 493        &mut settings.remove_trailing_whitespace_on_save,
 494        remove_trailing_whitespace_on_save,
 495    );
 496    merge(
 497        &mut settings.ensure_final_newline_on_save,
 498        ensure_final_newline_on_save,
 499    );
 500}
 501
 502impl settings::Settings for AllLanguageSettings {
 503    fn from_settings(content: &settings::SettingsContent) -> Self {
 504        let all_languages = &content.project.all_languages;
 505
 506        fn load_from_content(settings: LanguageSettingsContent) -> LanguageSettings {
 507            let inlay_hints = settings.inlay_hints.unwrap();
 508            let completions = settings.completions.unwrap();
 509            let prettier = settings.prettier.unwrap();
 510            let indent_guides = settings.indent_guides.unwrap();
 511            let tasks = settings.tasks.unwrap();
 512            let whitespace_map = settings.whitespace_map.unwrap();
 513
 514            LanguageSettings {
 515                tab_size: settings.tab_size.unwrap(),
 516                hard_tabs: settings.hard_tabs.unwrap(),
 517                soft_wrap: settings.soft_wrap.unwrap(),
 518                preferred_line_length: settings.preferred_line_length.unwrap(),
 519                show_wrap_guides: settings.show_wrap_guides.unwrap(),
 520                wrap_guides: settings.wrap_guides.unwrap(),
 521                indent_guides: IndentGuideSettings {
 522                    enabled: indent_guides.enabled.unwrap(),
 523                    line_width: indent_guides.line_width.unwrap(),
 524                    active_line_width: indent_guides.active_line_width.unwrap(),
 525                    coloring: indent_guides.coloring.unwrap(),
 526                    background_coloring: indent_guides.background_coloring.unwrap(),
 527                },
 528                format_on_save: settings.format_on_save.unwrap(),
 529                remove_trailing_whitespace_on_save: settings
 530                    .remove_trailing_whitespace_on_save
 531                    .unwrap(),
 532                ensure_final_newline_on_save: settings.ensure_final_newline_on_save.unwrap(),
 533                formatter: settings.formatter.unwrap(),
 534                prettier: PrettierSettings {
 535                    allowed: prettier.allowed.unwrap(),
 536                    parser: prettier.parser,
 537                    plugins: prettier.plugins,
 538                    options: prettier.options,
 539                },
 540                jsx_tag_auto_close: settings.jsx_tag_auto_close.unwrap().enabled.unwrap(),
 541                enable_language_server: settings.enable_language_server.unwrap(),
 542                language_servers: settings.language_servers.unwrap(),
 543                allow_rewrap: settings.allow_rewrap.unwrap(),
 544                show_edit_predictions: settings.show_edit_predictions.unwrap(),
 545                edit_predictions_disabled_in: settings.edit_predictions_disabled_in.unwrap(),
 546                show_whitespaces: settings.show_whitespaces.unwrap(),
 547                whitespace_map: WhitespaceMap {
 548                    space: SharedString::new(whitespace_map.space.unwrap().to_string()),
 549                    tab: SharedString::new(whitespace_map.tab.unwrap().to_string()),
 550                },
 551                extend_comment_on_newline: settings.extend_comment_on_newline.unwrap(),
 552                inlay_hints: InlayHintSettings {
 553                    enabled: inlay_hints.enabled.unwrap(),
 554                    show_value_hints: inlay_hints.show_value_hints.unwrap(),
 555                    show_type_hints: inlay_hints.show_type_hints.unwrap(),
 556                    show_parameter_hints: inlay_hints.show_parameter_hints.unwrap(),
 557                    show_other_hints: inlay_hints.show_other_hints.unwrap(),
 558                    show_background: inlay_hints.show_background.unwrap(),
 559                    edit_debounce_ms: inlay_hints.edit_debounce_ms.unwrap(),
 560                    scroll_debounce_ms: inlay_hints.scroll_debounce_ms.unwrap(),
 561                    toggle_on_modifiers_press: inlay_hints.toggle_on_modifiers_press,
 562                },
 563                use_autoclose: settings.use_autoclose.unwrap(),
 564                use_auto_surround: settings.use_auto_surround.unwrap(),
 565                use_on_type_format: settings.use_on_type_format.unwrap(),
 566                auto_indent: settings.auto_indent.unwrap(),
 567                auto_indent_on_paste: settings.auto_indent_on_paste.unwrap(),
 568                always_treat_brackets_as_autoclosed: settings
 569                    .always_treat_brackets_as_autoclosed
 570                    .unwrap(),
 571                code_actions_on_format: settings.code_actions_on_format.unwrap(),
 572                linked_edits: settings.linked_edits.unwrap(),
 573                tasks: LanguageTaskSettings {
 574                    variables: tasks.variables,
 575                    enabled: tasks.enabled.unwrap(),
 576                    prefer_lsp: tasks.prefer_lsp.unwrap(),
 577                },
 578                show_completions_on_input: settings.show_completions_on_input.unwrap(),
 579                show_completion_documentation: settings.show_completion_documentation.unwrap(),
 580                completions: CompletionSettings {
 581                    words: completions.words.unwrap(),
 582                    words_min_length: completions.words_min_length.unwrap(),
 583                    lsp: completions.lsp.unwrap(),
 584                    lsp_fetch_timeout_ms: completions.lsp_fetch_timeout_ms.unwrap(),
 585                    lsp_insert_mode: completions.lsp_insert_mode.unwrap(),
 586                },
 587                debuggers: settings.debuggers.unwrap(),
 588            }
 589        }
 590
 591        let default_language_settings = load_from_content(all_languages.defaults.clone());
 592
 593        let mut languages = HashMap::default();
 594        for (language_name, settings) in &all_languages.languages.0 {
 595            let mut language_settings = all_languages.defaults.clone();
 596            settings::merge_from::MergeFrom::merge_from(&mut language_settings, settings);
 597            languages.insert(
 598                LanguageName(language_name.clone()),
 599                load_from_content(language_settings),
 600            );
 601        }
 602
 603        let edit_prediction_provider = all_languages
 604            .features
 605            .as_ref()
 606            .and_then(|f| f.edit_prediction_provider);
 607
 608        let edit_predictions = all_languages.edit_predictions.clone().unwrap();
 609        let edit_predictions_mode = edit_predictions.mode.unwrap();
 610
 611        let disabled_globs: HashSet<&String> = edit_predictions
 612            .disabled_globs
 613            .as_ref()
 614            .unwrap()
 615            .iter()
 616            .collect();
 617
 618        let copilot = edit_predictions.copilot.unwrap();
 619        let copilot_settings = CopilotSettings {
 620            proxy: copilot.proxy,
 621            proxy_no_verify: copilot.proxy_no_verify,
 622            enterprise_uri: copilot.enterprise_uri,
 623        };
 624
 625        let enabled_in_text_threads = edit_predictions.enabled_in_text_threads.unwrap();
 626
 627        let mut file_types: FxHashMap<Arc<str>, GlobSet> = FxHashMap::default();
 628
 629        for (language, patterns) in &all_languages.file_types {
 630            let mut builder = GlobSetBuilder::new();
 631
 632            for pattern in &patterns.0 {
 633                builder.add(Glob::new(pattern).unwrap());
 634            }
 635
 636            file_types.insert(language.clone(), builder.build().unwrap());
 637        }
 638
 639        Self {
 640            edit_predictions: EditPredictionSettings {
 641                provider: if let Some(provider) = edit_prediction_provider {
 642                    provider
 643                } else {
 644                    EditPredictionProvider::None
 645                },
 646                disabled_globs: disabled_globs
 647                    .iter()
 648                    .filter_map(|g| {
 649                        let expanded_g = shellexpand::tilde(g).into_owned();
 650                        Some(DisabledGlob {
 651                            matcher: globset::Glob::new(&expanded_g).ok()?.compile_matcher(),
 652                            is_absolute: Path::new(&expanded_g).is_absolute(),
 653                        })
 654                    })
 655                    .collect(),
 656                mode: edit_predictions_mode,
 657                copilot: copilot_settings,
 658                enabled_in_text_threads,
 659            },
 660            defaults: default_language_settings,
 661            languages,
 662            file_types,
 663        }
 664    }
 665
 666    fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut SettingsContent) {
 667        let d = &mut current.project.all_languages.defaults;
 668        if let Some(size) = vscode
 669            .read_value("editor.tabSize")
 670            .and_then(|v| v.as_u64())
 671            .and_then(|n| NonZeroU32::new(n as u32))
 672        {
 673            d.tab_size = Some(size);
 674        }
 675        if let Some(v) = vscode.read_bool("editor.insertSpaces") {
 676            d.hard_tabs = Some(!v);
 677        }
 678
 679        vscode.enum_setting("editor.wordWrap", &mut d.soft_wrap, |s| match s {
 680            "on" => Some(SoftWrap::EditorWidth),
 681            "wordWrapColumn" => Some(SoftWrap::PreferLine),
 682            "bounded" => Some(SoftWrap::Bounded),
 683            "off" => Some(SoftWrap::None),
 684            _ => None,
 685        });
 686        vscode.u32_setting("editor.wordWrapColumn", &mut d.preferred_line_length);
 687
 688        if let Some(arr) = vscode
 689            .read_value("editor.rulers")
 690            .and_then(|v| v.as_array())
 691            .map(|v| v.iter().map(|n| n.as_u64().map(|n| n as usize)).collect())
 692        {
 693            d.wrap_guides = arr;
 694        }
 695        if let Some(b) = vscode.read_bool("editor.guides.indentation") {
 696            d.indent_guides.get_or_insert_default().enabled = Some(b);
 697        }
 698
 699        if let Some(b) = vscode.read_bool("editor.guides.formatOnSave") {
 700            d.format_on_save = Some(if b {
 701                FormatOnSave::On
 702            } else {
 703                FormatOnSave::Off
 704            });
 705        }
 706        vscode.bool_setting(
 707            "editor.trimAutoWhitespace",
 708            &mut d.remove_trailing_whitespace_on_save,
 709        );
 710        vscode.bool_setting(
 711            "files.insertFinalNewline",
 712            &mut d.ensure_final_newline_on_save,
 713        );
 714        vscode.bool_setting("editor.inlineSuggest.enabled", &mut d.show_edit_predictions);
 715        vscode.enum_setting("editor.renderWhitespace", &mut d.show_whitespaces, |s| {
 716            Some(match s {
 717                "boundary" => ShowWhitespaceSetting::Boundary,
 718                "trailing" => ShowWhitespaceSetting::Trailing,
 719                "selection" => ShowWhitespaceSetting::Selection,
 720                "all" => ShowWhitespaceSetting::All,
 721                _ => ShowWhitespaceSetting::None,
 722            })
 723        });
 724        vscode.enum_setting(
 725            "editor.autoSurround",
 726            &mut d.use_auto_surround,
 727            |s| match s {
 728                "languageDefined" | "quotes" | "brackets" => Some(true),
 729                "never" => Some(false),
 730                _ => None,
 731            },
 732        );
 733        vscode.bool_setting("editor.formatOnType", &mut d.use_on_type_format);
 734        vscode.bool_setting("editor.linkedEditing", &mut d.linked_edits);
 735        vscode.bool_setting("editor.formatOnPaste", &mut d.auto_indent_on_paste);
 736        vscode.bool_setting(
 737            "editor.suggestOnTriggerCharacters",
 738            &mut d.show_completions_on_input,
 739        );
 740        if let Some(b) = vscode.read_bool("editor.suggest.showWords") {
 741            let mode = if b {
 742                WordsCompletionMode::Enabled
 743            } else {
 744                WordsCompletionMode::Disabled
 745            };
 746            d.completions.get_or_insert_default().words = Some(mode);
 747        }
 748        // TODO: pull ^ out into helper and reuse for per-language settings
 749
 750        // vscodes file association map is inverted from ours, so we flip the mapping before merging
 751        let mut associations: HashMap<Arc<str>, ExtendingVec<String>> = HashMap::default();
 752        if let Some(map) = vscode
 753            .read_value("files.associations")
 754            .and_then(|v| v.as_object())
 755        {
 756            for (k, v) in map {
 757                let Some(v) = v.as_str() else { continue };
 758                associations.entry(v.into()).or_default().0.push(k.clone());
 759            }
 760        }
 761
 762        // TODO: do we want to merge imported globs per filetype? for now we'll just replace
 763        current
 764            .project
 765            .all_languages
 766            .file_types
 767            .extend(associations);
 768
 769        // cursor global ignore list applies to cursor-tab, so transfer it to edit_predictions.disabled_globs
 770        if let Some(disabled_globs) = vscode
 771            .read_value("cursor.general.globalCursorIgnoreList")
 772            .and_then(|v| v.as_array())
 773        {
 774            current
 775                .project
 776                .all_languages
 777                .edit_predictions
 778                .get_or_insert_default()
 779                .disabled_globs
 780                .get_or_insert_default()
 781                .extend(
 782                    disabled_globs
 783                        .iter()
 784                        .filter_map(|glob| glob.as_str())
 785                        .map(|s| s.to_string()),
 786                );
 787        }
 788    }
 789}
 790
 791#[derive(Default, Debug, Clone, PartialEq, Eq)]
 792pub struct JsxTagAutoCloseSettings {
 793    /// Enables or disables auto-closing of JSX tags.
 794    pub enabled: bool,
 795}
 796
 797#[cfg(test)]
 798mod tests {
 799    use super::*;
 800    use gpui::TestAppContext;
 801    use util::rel_path::rel_path;
 802
 803    #[gpui::test]
 804    fn test_edit_predictions_enabled_for_file(cx: &mut TestAppContext) {
 805        use crate::TestFile;
 806        use std::path::PathBuf;
 807
 808        let cx = cx.app.borrow_mut();
 809
 810        let build_settings = |globs: &[&str]| -> EditPredictionSettings {
 811            EditPredictionSettings {
 812                disabled_globs: globs
 813                    .iter()
 814                    .map(|glob_str| {
 815                        #[cfg(windows)]
 816                        let glob_str = {
 817                            let mut g = String::new();
 818
 819                            if glob_str.starts_with('/') {
 820                                g.push_str("C:");
 821                            }
 822
 823                            g.push_str(&glob_str.replace('/', "\\"));
 824                            g
 825                        };
 826                        #[cfg(windows)]
 827                        let glob_str = glob_str.as_str();
 828                        let expanded_glob_str = shellexpand::tilde(glob_str).into_owned();
 829                        DisabledGlob {
 830                            matcher: globset::Glob::new(&expanded_glob_str)
 831                                .unwrap()
 832                                .compile_matcher(),
 833                            is_absolute: Path::new(&expanded_glob_str).is_absolute(),
 834                        }
 835                    })
 836                    .collect(),
 837                ..Default::default()
 838            }
 839        };
 840
 841        const WORKTREE_NAME: &str = "project";
 842        let make_test_file = |segments: &[&str]| -> Arc<dyn File> {
 843            let path = segments.join("/");
 844            let path = rel_path(&path);
 845
 846            Arc::new(TestFile {
 847                path: path.into(),
 848                root_name: WORKTREE_NAME.to_string(),
 849                local_root: Some(PathBuf::from(if cfg!(windows) {
 850                    "C:\\absolute\\"
 851                } else {
 852                    "/absolute/"
 853                })),
 854            })
 855        };
 856
 857        let test_file = make_test_file(&["src", "test", "file.rs"]);
 858
 859        // Test relative globs
 860        let settings = build_settings(&["*.rs"]);
 861        assert!(!settings.enabled_for_file(&test_file, &cx));
 862        let settings = build_settings(&["*.txt"]);
 863        assert!(settings.enabled_for_file(&test_file, &cx));
 864
 865        // Test absolute globs
 866        let settings = build_settings(&["/absolute/**/*.rs"]);
 867        assert!(!settings.enabled_for_file(&test_file, &cx));
 868        let settings = build_settings(&["/other/**/*.rs"]);
 869        assert!(settings.enabled_for_file(&test_file, &cx));
 870
 871        // Test exact path match relative
 872        let settings = build_settings(&["src/test/file.rs"]);
 873        assert!(!settings.enabled_for_file(&test_file, &cx));
 874        let settings = build_settings(&["src/test/otherfile.rs"]);
 875        assert!(settings.enabled_for_file(&test_file, &cx));
 876
 877        // Test exact path match absolute
 878        let settings = build_settings(&[&format!("/absolute/{}/src/test/file.rs", WORKTREE_NAME)]);
 879        assert!(!settings.enabled_for_file(&test_file, &cx));
 880        let settings = build_settings(&["/other/test/otherfile.rs"]);
 881        assert!(settings.enabled_for_file(&test_file, &cx));
 882
 883        // Test * glob
 884        let settings = build_settings(&["*"]);
 885        assert!(!settings.enabled_for_file(&test_file, &cx));
 886        let settings = build_settings(&["*.txt"]);
 887        assert!(settings.enabled_for_file(&test_file, &cx));
 888
 889        // Test **/* glob
 890        let settings = build_settings(&["**/*"]);
 891        assert!(!settings.enabled_for_file(&test_file, &cx));
 892        let settings = build_settings(&["other/**/*"]);
 893        assert!(settings.enabled_for_file(&test_file, &cx));
 894
 895        // Test directory/** glob
 896        let settings = build_settings(&["src/**"]);
 897        assert!(!settings.enabled_for_file(&test_file, &cx));
 898
 899        let test_file_root: Arc<dyn File> = Arc::new(TestFile {
 900            path: rel_path("file.rs").into(),
 901            root_name: WORKTREE_NAME.to_string(),
 902            local_root: Some(PathBuf::from("/absolute/")),
 903        });
 904        assert!(settings.enabled_for_file(&test_file_root, &cx));
 905
 906        let settings = build_settings(&["other/**"]);
 907        assert!(settings.enabled_for_file(&test_file, &cx));
 908
 909        // Test **/directory/* glob
 910        let settings = build_settings(&["**/test/*"]);
 911        assert!(!settings.enabled_for_file(&test_file, &cx));
 912        let settings = build_settings(&["**/other/*"]);
 913        assert!(settings.enabled_for_file(&test_file, &cx));
 914
 915        // Test multiple globs
 916        let settings = build_settings(&["*.rs", "*.txt", "src/**"]);
 917        assert!(!settings.enabled_for_file(&test_file, &cx));
 918        let settings = build_settings(&["*.txt", "*.md", "other/**"]);
 919        assert!(settings.enabled_for_file(&test_file, &cx));
 920
 921        // Test dot files
 922        let dot_file = make_test_file(&[".config", "settings.json"]);
 923        let settings = build_settings(&[".*/**"]);
 924        assert!(!settings.enabled_for_file(&dot_file, &cx));
 925
 926        let dot_env_file = make_test_file(&[".env"]);
 927        let settings = build_settings(&[".env"]);
 928        assert!(!settings.enabled_for_file(&dot_env_file, &cx));
 929
 930        // Test tilde expansion
 931        let home = shellexpand::tilde("~").into_owned();
 932        let home_file = Arc::new(TestFile {
 933            path: rel_path("test.rs").into(),
 934            root_name: "the-dir".to_string(),
 935            local_root: Some(PathBuf::from(home)),
 936        }) as Arc<dyn File>;
 937        let settings = build_settings(&["~/the-dir/test.rs"]);
 938        assert!(!settings.enabled_for_file(&home_file, &cx));
 939    }
 940
 941    #[test]
 942    fn test_resolve_language_servers() {
 943        fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
 944            names
 945                .iter()
 946                .copied()
 947                .map(|name| LanguageServerName(name.to_string().into()))
 948                .collect::<Vec<_>>()
 949        }
 950
 951        let available_language_servers = language_server_names(&[
 952            "typescript-language-server",
 953            "biome",
 954            "deno",
 955            "eslint",
 956            "tailwind",
 957        ]);
 958
 959        // A value of just `["..."]` is the same as taking all of the available language servers.
 960        assert_eq!(
 961            LanguageSettings::resolve_language_servers(
 962                &[LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()],
 963                &available_language_servers,
 964            ),
 965            available_language_servers
 966        );
 967
 968        // Referencing one of the available language servers will change its order.
 969        assert_eq!(
 970            LanguageSettings::resolve_language_servers(
 971                &[
 972                    "biome".into(),
 973                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into(),
 974                    "deno".into()
 975                ],
 976                &available_language_servers
 977            ),
 978            language_server_names(&[
 979                "biome",
 980                "typescript-language-server",
 981                "eslint",
 982                "tailwind",
 983                "deno",
 984            ])
 985        );
 986
 987        // Negating an available language server removes it from the list.
 988        assert_eq!(
 989            LanguageSettings::resolve_language_servers(
 990                &[
 991                    "deno".into(),
 992                    "!typescript-language-server".into(),
 993                    "!biome".into(),
 994                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
 995                ],
 996                &available_language_servers
 997            ),
 998            language_server_names(&["deno", "eslint", "tailwind"])
 999        );
1000
1001        // Adding a language server not in the list of available language servers adds it to the list.
1002        assert_eq!(
1003            LanguageSettings::resolve_language_servers(
1004                &[
1005                    "my-cool-language-server".into(),
1006                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1007                ],
1008                &available_language_servers
1009            ),
1010            language_server_names(&[
1011                "my-cool-language-server",
1012                "typescript-language-server",
1013                "biome",
1014                "deno",
1015                "eslint",
1016                "tailwind",
1017            ])
1018        );
1019    }
1020}