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