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