language.rs

   1use std::{num::NonZeroU32, path::Path};
   2
   3use collections::{HashMap, HashSet};
   4use schemars::JsonSchema;
   5use serde::{Deserialize, Serialize, de::Error as _};
   6use settings_macros::{MergeFrom, with_fallible_options};
   7use std::sync::Arc;
   8
   9use crate::{ExtendingVec, merge_from};
  10
  11/// The state of the modifier keys at some point in time
  12#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
  13pub struct ModifiersContent {
  14    /// The control key
  15    #[serde(default)]
  16    pub control: bool,
  17    /// The alt key
  18    /// Sometimes also known as the 'meta' key
  19    #[serde(default)]
  20    pub alt: bool,
  21    /// The shift key
  22    #[serde(default)]
  23    pub shift: bool,
  24    /// The command key, on macos
  25    /// the windows key, on windows
  26    /// the super key, on linux
  27    #[serde(default)]
  28    pub platform: bool,
  29    /// The function key
  30    #[serde(default)]
  31    pub function: bool,
  32}
  33
  34#[with_fallible_options]
  35#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
  36pub struct AllLanguageSettingsContent {
  37    /// The settings for enabling/disabling features.
  38    pub features: Option<FeaturesContent>,
  39    /// The edit prediction settings.
  40    pub edit_predictions: Option<EditPredictionSettingsContent>,
  41    /// The default language settings.
  42    #[serde(flatten)]
  43    pub defaults: LanguageSettingsContent,
  44    /// The settings for individual languages.
  45    #[serde(default)]
  46    pub languages: LanguageToSettingsMap,
  47    /// Settings for associating file extensions and filenames
  48    /// with languages.
  49    pub file_types: Option<HashMap<Arc<str>, ExtendingVec<String>>>,
  50}
  51
  52impl merge_from::MergeFrom for AllLanguageSettingsContent {
  53    fn merge_from(&mut self, other: &Self) {
  54        self.file_types.merge_from(&other.file_types);
  55        self.features.merge_from(&other.features);
  56        self.edit_predictions.merge_from(&other.edit_predictions);
  57
  58        // A user's global settings override the default global settings and
  59        // all default language-specific settings.
  60        //
  61        self.defaults.merge_from(&other.defaults);
  62        for language_settings in self.languages.0.values_mut() {
  63            language_settings.merge_from(&other.defaults);
  64        }
  65
  66        // A user's language-specific settings override default language-specific settings.
  67        for (language_name, user_language_settings) in &other.languages.0 {
  68            if let Some(existing) = self.languages.0.get_mut(language_name) {
  69                existing.merge_from(&user_language_settings);
  70            } else {
  71                let mut new_settings = self.defaults.clone();
  72                new_settings.merge_from(&user_language_settings);
  73
  74                self.languages.0.insert(language_name.clone(), new_settings);
  75            }
  76        }
  77    }
  78}
  79
  80/// The settings for enabling/disabling features.
  81#[with_fallible_options]
  82#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
  83#[serde(rename_all = "snake_case")]
  84pub struct FeaturesContent {
  85    /// Determines which edit prediction provider to use.
  86    pub edit_prediction_provider: Option<EditPredictionProvider>,
  87}
  88
  89/// The provider that supplies edit predictions.
  90#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, JsonSchema, MergeFrom)]
  91#[serde(rename_all = "snake_case")]
  92pub enum EditPredictionProvider {
  93    None,
  94    #[default]
  95    Copilot,
  96    Supermaven,
  97    Zed,
  98    Codestral,
  99    Experimental(&'static str),
 100}
 101
 102pub const EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME: &str = "sweep";
 103pub const EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME: &str = "zeta2";
 104pub const EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME: &str = "mercury";
 105
 106impl<'de> Deserialize<'de> for EditPredictionProvider {
 107    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 108    where
 109        D: serde::Deserializer<'de>,
 110    {
 111        #[derive(Deserialize)]
 112        #[serde(rename_all = "snake_case")]
 113        pub enum Content {
 114            None,
 115            Copilot,
 116            Supermaven,
 117            Zed,
 118            Codestral,
 119            Experimental(String),
 120        }
 121
 122        Ok(match Content::deserialize(deserializer)? {
 123            Content::None => EditPredictionProvider::None,
 124            Content::Copilot => EditPredictionProvider::Copilot,
 125            Content::Supermaven => EditPredictionProvider::Supermaven,
 126            Content::Zed => EditPredictionProvider::Zed,
 127            Content::Codestral => EditPredictionProvider::Codestral,
 128            Content::Experimental(name)
 129                if name == EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME =>
 130            {
 131                EditPredictionProvider::Experimental(
 132                    EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
 133                )
 134            }
 135            Content::Experimental(name)
 136                if name == EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME =>
 137            {
 138                EditPredictionProvider::Experimental(
 139                    EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
 140                )
 141            }
 142            Content::Experimental(name)
 143                if name == EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME =>
 144            {
 145                EditPredictionProvider::Experimental(
 146                    EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
 147                )
 148            }
 149            Content::Experimental(name) => {
 150                return Err(D::Error::custom(format!(
 151                    "Unknown experimental edit prediction provider: {}",
 152                    name
 153                )));
 154            }
 155        })
 156    }
 157}
 158
 159impl EditPredictionProvider {
 160    pub fn is_zed(&self) -> bool {
 161        match self {
 162            EditPredictionProvider::Zed => true,
 163            EditPredictionProvider::None
 164            | EditPredictionProvider::Copilot
 165            | EditPredictionProvider::Supermaven
 166            | EditPredictionProvider::Codestral
 167            | EditPredictionProvider::Experimental(_) => false,
 168        }
 169    }
 170
 171    pub fn display_name(&self) -> Option<&'static str> {
 172        match self {
 173            EditPredictionProvider::Zed => Some("Zed AI"),
 174            EditPredictionProvider::Copilot => Some("GitHub Copilot"),
 175            EditPredictionProvider::Supermaven => Some("Supermaven"),
 176            EditPredictionProvider::Codestral => Some("Codestral"),
 177            EditPredictionProvider::Experimental(
 178                EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
 179            ) => Some("Sweep"),
 180            EditPredictionProvider::Experimental(
 181                EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
 182            ) => Some("Mercury"),
 183            EditPredictionProvider::Experimental(
 184                EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
 185            ) => Some("Zeta2"),
 186            EditPredictionProvider::None | EditPredictionProvider::Experimental(_) => None,
 187        }
 188    }
 189}
 190
 191/// The contents of the edit prediction settings.
 192#[with_fallible_options]
 193#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
 194pub struct EditPredictionSettingsContent {
 195    /// A list of globs representing files that edit predictions should be disabled for.
 196    /// This list adds to a pre-existing, sensible default set of globs.
 197    /// Any additional ones you add are combined with them.
 198    pub disabled_globs: Option<Vec<String>>,
 199    /// The mode used to display edit predictions in the buffer.
 200    /// Provider support required.
 201    pub mode: Option<EditPredictionsMode>,
 202    /// Settings specific to GitHub Copilot.
 203    pub copilot: Option<CopilotSettingsContent>,
 204    /// Settings specific to Codestral.
 205    pub codestral: Option<CodestralSettingsContent>,
 206    /// Whether edit predictions are enabled in the assistant prompt editor.
 207    /// This has no effect if globally disabled.
 208    pub enabled_in_text_threads: Option<bool>,
 209    /// The directory where manually captured edit prediction examples are stored.
 210    pub examples_dir: Option<Arc<Path>>,
 211    /// The number of edit prediction examples captured per ten thousand predictions.
 212    pub example_capture_rate: Option<u16>,
 213}
 214
 215#[with_fallible_options]
 216#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
 217pub struct CopilotSettingsContent {
 218    /// HTTP/HTTPS proxy to use for Copilot.
 219    ///
 220    /// Default: none
 221    pub proxy: Option<String>,
 222    /// Disable certificate verification for the proxy (not recommended).
 223    ///
 224    /// Default: false
 225    pub proxy_no_verify: Option<bool>,
 226    /// Enterprise URI for Copilot.
 227    ///
 228    /// Default: none
 229    pub enterprise_uri: Option<String>,
 230    /// Whether the Copilot Next Edit Suggestions feature is enabled.
 231    ///
 232    /// Default: true
 233    pub enable_next_edit_suggestions: Option<bool>,
 234}
 235
 236#[with_fallible_options]
 237#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
 238pub struct CodestralSettingsContent {
 239    /// Model to use for completions.
 240    ///
 241    /// Default: "codestral-latest"
 242    pub model: Option<String>,
 243    /// Maximum tokens to generate.
 244    ///
 245    /// Default: 150
 246    pub max_tokens: Option<u32>,
 247    /// Api URL to use for completions.
 248    ///
 249    /// Default: "https://codestral.mistral.ai"
 250    pub api_url: Option<String>,
 251}
 252
 253/// The mode in which edit predictions should be displayed.
 254#[derive(
 255    Copy,
 256    Clone,
 257    Debug,
 258    Default,
 259    Eq,
 260    PartialEq,
 261    Serialize,
 262    Deserialize,
 263    JsonSchema,
 264    MergeFrom,
 265    strum::VariantArray,
 266    strum::VariantNames,
 267)]
 268#[serde(rename_all = "snake_case")]
 269pub enum EditPredictionsMode {
 270    /// If provider supports it, display inline when holding modifier key (e.g., alt).
 271    /// Otherwise, eager preview is used.
 272    #[serde(alias = "auto")]
 273    Subtle,
 274    /// Display inline when there are no language server completions available.
 275    #[default]
 276    #[serde(alias = "eager_preview")]
 277    Eager,
 278}
 279
 280/// Controls the soft-wrapping behavior in the editor.
 281#[derive(
 282    Copy,
 283    Clone,
 284    Debug,
 285    Serialize,
 286    Deserialize,
 287    PartialEq,
 288    Eq,
 289    JsonSchema,
 290    MergeFrom,
 291    strum::VariantArray,
 292    strum::VariantNames,
 293)]
 294#[serde(rename_all = "snake_case")]
 295pub enum SoftWrap {
 296    /// Prefer a single line generally, unless an overly long line is encountered.
 297    None,
 298    /// Deprecated: use None instead. Left to avoid breaking existing users' configs.
 299    /// Prefer a single line generally, unless an overly long line is encountered.
 300    PreferLine,
 301    /// Soft wrap lines that exceed the editor width.
 302    EditorWidth,
 303    /// Soft wrap lines at the preferred line length.
 304    PreferredLineLength,
 305    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
 306    Bounded,
 307}
 308
 309/// The settings for a particular language.
 310#[with_fallible_options]
 311#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
 312pub struct LanguageSettingsContent {
 313    /// How many columns a tab should occupy.
 314    ///
 315    /// Default: 4
 316    #[schemars(range(min = 1, max = 128))]
 317    pub tab_size: Option<NonZeroU32>,
 318    /// Whether to indent lines using tab characters, as opposed to multiple
 319    /// spaces.
 320    ///
 321    /// Default: false
 322    pub hard_tabs: Option<bool>,
 323    /// How to soft-wrap long lines of text.
 324    ///
 325    /// Default: none
 326    pub soft_wrap: Option<SoftWrap>,
 327    /// The column at which to soft-wrap lines, for buffers where soft-wrap
 328    /// is enabled.
 329    ///
 330    /// Default: 80
 331    pub preferred_line_length: Option<u32>,
 332    /// Whether to show wrap guides in the editor. Setting this to true will
 333    /// show a guide at the 'preferred_line_length' value if softwrap is set to
 334    /// 'preferred_line_length', and will show any additional guides as specified
 335    /// by the 'wrap_guides' setting.
 336    ///
 337    /// Default: true
 338    pub show_wrap_guides: Option<bool>,
 339    /// Character counts at which to show wrap guides in the editor.
 340    ///
 341    /// Default: []
 342    pub wrap_guides: Option<Vec<usize>>,
 343    /// Indent guide related settings.
 344    pub indent_guides: Option<IndentGuideSettingsContent>,
 345    /// Whether or not to perform a buffer format before saving.
 346    ///
 347    /// Default: on
 348    pub format_on_save: Option<FormatOnSave>,
 349    /// Whether or not to remove any trailing whitespace from lines of a buffer
 350    /// before saving it.
 351    ///
 352    /// Default: true
 353    pub remove_trailing_whitespace_on_save: Option<bool>,
 354    /// Whether or not to ensure there's a single newline at the end of a buffer
 355    /// when saving it.
 356    ///
 357    /// Default: true
 358    pub ensure_final_newline_on_save: Option<bool>,
 359    /// How to perform a buffer format.
 360    ///
 361    /// Default: auto
 362    pub formatter: Option<FormatterList>,
 363    /// Zed's Prettier integration settings.
 364    /// Allows to enable/disable formatting with Prettier
 365    /// and configure default Prettier, used when no project-level Prettier installation is found.
 366    ///
 367    /// Default: off
 368    pub prettier: Option<PrettierSettingsContent>,
 369    /// Whether to automatically close JSX tags.
 370    pub jsx_tag_auto_close: Option<JsxTagAutoCloseSettingsContent>,
 371    /// Whether to use language servers to provide code intelligence.
 372    ///
 373    /// Default: true
 374    pub enable_language_server: Option<bool>,
 375    /// The list of language servers to use (or disable) for this language.
 376    ///
 377    /// This array should consist of language server IDs, as well as the following
 378    /// special tokens:
 379    /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
 380    /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
 381    ///
 382    /// Default: ["..."]
 383    pub language_servers: Option<Vec<String>>,
 384    /// Controls where the `editor::Rewrap` action is allowed for this language.
 385    ///
 386    /// Note: This setting has no effect in Vim mode, as rewrap is already
 387    /// allowed everywhere.
 388    ///
 389    /// Default: "in_comments"
 390    pub allow_rewrap: Option<RewrapBehavior>,
 391    /// Controls whether edit predictions are shown immediately (true)
 392    /// or manually by triggering `editor::ShowEditPrediction` (false).
 393    ///
 394    /// Default: true
 395    pub show_edit_predictions: Option<bool>,
 396    /// Controls whether edit predictions are shown in the given language
 397    /// scopes.
 398    ///
 399    /// Example: ["string", "comment"]
 400    ///
 401    /// Default: []
 402    pub edit_predictions_disabled_in: Option<Vec<String>>,
 403    /// Whether to show tabs and spaces in the editor.
 404    pub show_whitespaces: Option<ShowWhitespaceSetting>,
 405    /// Visible characters used to render whitespace when show_whitespaces is enabled.
 406    ///
 407    /// Default: "•" for spaces, "→" for tabs.
 408    pub whitespace_map: Option<WhitespaceMapContent>,
 409    /// Whether to start a new line with a comment when a previous line is a comment as well.
 410    ///
 411    /// Default: true
 412    pub extend_comment_on_newline: Option<bool>,
 413    /// Whether to continue markdown lists when pressing enter.
 414    ///
 415    /// Default: true
 416    pub extend_list_on_newline: Option<bool>,
 417    /// Whether to indent list items when pressing tab after a list marker.
 418    ///
 419    /// Default: true
 420    pub indent_list_on_tab: Option<bool>,
 421    /// Inlay hint related settings.
 422    pub inlay_hints: Option<InlayHintSettingsContent>,
 423    /// Whether to automatically type closing characters for you. For example,
 424    /// when you type '(', Zed will automatically add a closing ')' at the correct position.
 425    ///
 426    /// Default: true
 427    pub use_autoclose: Option<bool>,
 428    /// Whether to automatically surround text with characters for you. For example,
 429    /// when you select text and type '(', Zed will automatically surround text with ().
 430    ///
 431    /// Default: true
 432    pub use_auto_surround: Option<bool>,
 433    /// Controls how the editor handles the autoclosed characters.
 434    /// When set to `false`(default), skipping over and auto-removing of the closing characters
 435    /// happen only for auto-inserted characters.
 436    /// Otherwise(when `true`), the closing characters are always skipped over and auto-removed
 437    /// no matter how they were inserted.
 438    ///
 439    /// Default: false
 440    pub always_treat_brackets_as_autoclosed: Option<bool>,
 441    /// Whether to use additional LSP queries to format (and amend) the code after
 442    /// every "trigger" symbol input, defined by LSP server capabilities.
 443    ///
 444    /// Default: true
 445    pub use_on_type_format: Option<bool>,
 446    /// Which code actions to run on save before the formatter.
 447    /// These are not run if formatting is off.
 448    ///
 449    /// Default: {} (or {"source.organizeImports": true} for Go).
 450    pub code_actions_on_format: Option<HashMap<String, bool>>,
 451    /// Whether to perform linked edits of associated ranges, if the language server supports it.
 452    /// For example, when editing opening <html> tag, the contents of the closing </html> tag will be edited as well.
 453    ///
 454    /// Default: true
 455    pub linked_edits: Option<bool>,
 456    /// Whether indentation should be adjusted based on the context whilst typing.
 457    ///
 458    /// Default: true
 459    pub auto_indent: Option<bool>,
 460    /// Whether indentation of pasted content should be adjusted based on the context.
 461    ///
 462    /// Default: true
 463    pub auto_indent_on_paste: Option<bool>,
 464    /// Task configuration for this language.
 465    ///
 466    /// Default: {}
 467    pub tasks: Option<LanguageTaskSettingsContent>,
 468    /// Whether to pop the completions menu while typing in an editor without
 469    /// explicitly requesting it.
 470    ///
 471    /// Default: true
 472    pub show_completions_on_input: Option<bool>,
 473    /// Whether to display inline and alongside documentation for items in the
 474    /// completions menu.
 475    ///
 476    /// Default: true
 477    pub show_completion_documentation: Option<bool>,
 478    /// Controls how completions are processed for this language.
 479    pub completions: Option<CompletionSettingsContent>,
 480    /// Preferred debuggers for this language.
 481    ///
 482    /// Default: []
 483    pub debuggers: Option<Vec<String>>,
 484    /// Whether to enable word diff highlighting in the editor.
 485    ///
 486    /// When enabled, changed words within modified lines are highlighted
 487    /// to show exactly what changed.
 488    ///
 489    /// Default: true
 490    pub word_diff_enabled: Option<bool>,
 491    /// Whether to use tree-sitter bracket queries to detect and colorize the brackets in the editor.
 492    ///
 493    /// Default: false
 494    pub colorize_brackets: Option<bool>,
 495}
 496
 497/// Controls how whitespace should be displayedin the editor.
 498#[derive(
 499    Copy,
 500    Clone,
 501    Debug,
 502    Serialize,
 503    Deserialize,
 504    PartialEq,
 505    Eq,
 506    JsonSchema,
 507    MergeFrom,
 508    strum::VariantArray,
 509    strum::VariantNames,
 510)]
 511#[serde(rename_all = "snake_case")]
 512pub enum ShowWhitespaceSetting {
 513    /// Draw whitespace only for the selected text.
 514    Selection,
 515    /// Do not draw any tabs or spaces.
 516    None,
 517    /// Draw all invisible symbols.
 518    All,
 519    /// Draw whitespaces at boundaries only.
 520    ///
 521    /// For a whitespace to be on a boundary, any of the following conditions need to be met:
 522    /// - It is a tab
 523    /// - It is adjacent to an edge (start or end)
 524    /// - It is adjacent to a whitespace (left or right)
 525    Boundary,
 526    /// Draw whitespaces only after non-whitespace characters.
 527    Trailing,
 528}
 529
 530#[with_fallible_options]
 531#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
 532pub struct WhitespaceMapContent {
 533    pub space: Option<char>,
 534    pub tab: Option<char>,
 535}
 536
 537/// The behavior of `editor::Rewrap`.
 538#[derive(
 539    Debug,
 540    PartialEq,
 541    Clone,
 542    Copy,
 543    Default,
 544    Serialize,
 545    Deserialize,
 546    JsonSchema,
 547    MergeFrom,
 548    strum::VariantArray,
 549    strum::VariantNames,
 550)]
 551#[serde(rename_all = "snake_case")]
 552pub enum RewrapBehavior {
 553    /// Only rewrap within comments.
 554    #[default]
 555    InComments,
 556    /// Only rewrap within the current selection(s).
 557    InSelections,
 558    /// Allow rewrapping anywhere.
 559    Anywhere,
 560}
 561
 562#[with_fallible_options]
 563#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
 564pub struct JsxTagAutoCloseSettingsContent {
 565    /// Enables or disables auto-closing of JSX tags.
 566    pub enabled: Option<bool>,
 567}
 568
 569/// The settings for inlay hints.
 570#[with_fallible_options]
 571#[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq, Eq)]
 572pub struct InlayHintSettingsContent {
 573    /// Global switch to toggle hints on and off.
 574    ///
 575    /// Default: false
 576    pub enabled: Option<bool>,
 577    /// Global switch to toggle inline values on and off when debugging.
 578    ///
 579    /// Default: true
 580    pub show_value_hints: Option<bool>,
 581    /// Whether type hints should be shown.
 582    ///
 583    /// Default: true
 584    pub show_type_hints: Option<bool>,
 585    /// Whether parameter hints should be shown.
 586    ///
 587    /// Default: true
 588    pub show_parameter_hints: Option<bool>,
 589    /// Whether other hints should be shown.
 590    ///
 591    /// Default: true
 592    pub show_other_hints: Option<bool>,
 593    /// Whether to show a background for inlay hints.
 594    ///
 595    /// If set to `true`, the background will use the `hint.background` color
 596    /// from the current theme.
 597    ///
 598    /// Default: false
 599    pub show_background: Option<bool>,
 600    /// Whether or not to debounce inlay hints updates after buffer edits.
 601    ///
 602    /// Set to 0 to disable debouncing.
 603    ///
 604    /// Default: 700
 605    pub edit_debounce_ms: Option<u64>,
 606    /// Whether or not to debounce inlay hints updates after buffer scrolls.
 607    ///
 608    /// Set to 0 to disable debouncing.
 609    ///
 610    /// Default: 50
 611    pub scroll_debounce_ms: Option<u64>,
 612    /// Toggles inlay hints (hides or shows) when the user presses the modifiers specified.
 613    /// If only a subset of the modifiers specified is pressed, hints are not toggled.
 614    /// If no modifiers are specified, this is equivalent to `null`.
 615    ///
 616    /// Default: null
 617    pub toggle_on_modifiers_press: Option<ModifiersContent>,
 618}
 619
 620/// The kind of an inlay hint.
 621#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 622pub enum InlayHintKind {
 623    /// An inlay hint for a type.
 624    Type,
 625    /// An inlay hint for a parameter.
 626    Parameter,
 627}
 628
 629impl InlayHintKind {
 630    /// Returns the [`InlayHintKind`]fromthe given name.
 631    ///
 632    /// Returns `None` if `name` does not match any of the expected
 633    /// string representations.
 634    pub fn from_name(name: &str) -> Option<Self> {
 635        match name {
 636            "type" => Some(InlayHintKind::Type),
 637            "parameter" => Some(InlayHintKind::Parameter),
 638            _ => None,
 639        }
 640    }
 641
 642    /// Returns the name of this [`InlayHintKind`].
 643    pub fn name(&self) -> &'static str {
 644        match self {
 645            InlayHintKind::Type => "type",
 646            InlayHintKind::Parameter => "parameter",
 647        }
 648    }
 649}
 650
 651/// Controls how completions are processed for this language.
 652#[with_fallible_options]
 653#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom, Default)]
 654#[serde(rename_all = "snake_case")]
 655pub struct CompletionSettingsContent {
 656    /// Controls how words are completed.
 657    /// For large documents, not all words may be fetched for completion.
 658    ///
 659    /// Default: `fallback`
 660    pub words: Option<WordsCompletionMode>,
 661    /// How many characters has to be in the completions query to automatically show the words-based completions.
 662    /// Before that value, it's still possible to trigger the words-based completion manually with the corresponding editor command.
 663    ///
 664    /// Default: 3
 665    pub words_min_length: Option<u32>,
 666    /// Whether to fetch LSP completions or not.
 667    ///
 668    /// Default: true
 669    pub lsp: Option<bool>,
 670    /// When fetching LSP completions, determines how long to wait for a response of a particular server.
 671    /// When set to 0, waits indefinitely.
 672    ///
 673    /// Default: 0
 674    pub lsp_fetch_timeout_ms: Option<u64>,
 675    /// Controls how LSP completions are inserted.
 676    ///
 677    /// Default: "replace_suffix"
 678    pub lsp_insert_mode: Option<LspInsertMode>,
 679}
 680
 681#[derive(
 682    Copy,
 683    Clone,
 684    Debug,
 685    Serialize,
 686    Deserialize,
 687    PartialEq,
 688    Eq,
 689    JsonSchema,
 690    MergeFrom,
 691    strum::VariantArray,
 692    strum::VariantNames,
 693)]
 694#[serde(rename_all = "snake_case")]
 695pub enum LspInsertMode {
 696    /// Replaces text before the cursor, using the `insert` range described in the LSP specification.
 697    Insert,
 698    /// Replaces text before and after the cursor, using the `replace` range described in the LSP specification.
 699    Replace,
 700    /// Behaves like `"replace"` if the text that would be replaced is a subsequence of the completion text,
 701    /// and like `"insert"` otherwise.
 702    ReplaceSubsequence,
 703    /// Behaves like `"replace"` if the text after the cursor is a suffix of the completion, and like
 704    /// `"insert"` otherwise.
 705    ReplaceSuffix,
 706}
 707
 708/// Controls how document's words are completed.
 709#[derive(
 710    Copy,
 711    Clone,
 712    Debug,
 713    Serialize,
 714    Deserialize,
 715    PartialEq,
 716    Eq,
 717    JsonSchema,
 718    MergeFrom,
 719    strum::VariantArray,
 720    strum::VariantNames,
 721)]
 722#[serde(rename_all = "snake_case")]
 723pub enum WordsCompletionMode {
 724    /// Always fetch document's words for completions along with LSP completions.
 725    Enabled,
 726    /// Only if LSP response errors or times out,
 727    /// use document's words to show completions.
 728    Fallback,
 729    /// Never fetch or complete document's words for completions.
 730    /// (Word-based completions can still be queried via a separate action)
 731    Disabled,
 732}
 733
 734/// Allows to enable/disable formatting with Prettier
 735/// and configure default Prettier, used when no project-level Prettier installation is found.
 736/// Prettier formatting is disabled by default.
 737#[with_fallible_options]
 738#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
 739pub struct PrettierSettingsContent {
 740    /// Enables or disables formatting with Prettier for a given language.
 741    pub allowed: Option<bool>,
 742
 743    /// Forces Prettier integration to use a specific parser name when formatting files with the language.
 744    pub parser: Option<String>,
 745
 746    /// Forces Prettier integration to use specific plugins when formatting files with the language.
 747    /// The default Prettier will be installed with these plugins.
 748    pub plugins: Option<HashSet<String>>,
 749
 750    /// Default Prettier options, in the format as in package.json section for Prettier.
 751    /// If project installs Prettier via its package.json, these options will be ignored.
 752    #[serde(flatten)]
 753    pub options: Option<HashMap<String, serde_json::Value>>,
 754}
 755
 756/// TODO: this should just be a bool
 757/// Controls the behavior of formatting files when they are saved.
 758#[derive(
 759    Debug,
 760    Clone,
 761    Copy,
 762    PartialEq,
 763    Eq,
 764    Serialize,
 765    Deserialize,
 766    JsonSchema,
 767    MergeFrom,
 768    strum::VariantArray,
 769    strum::VariantNames,
 770)]
 771#[serde(rename_all = "lowercase")]
 772pub enum FormatOnSave {
 773    /// Files should be formatted on save.
 774    On,
 775    /// Files should not be formatted on save.
 776    Off,
 777}
 778
 779/// Controls which formatters should be used when formatting code.
 780#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 781#[serde(untagged)]
 782pub enum FormatterList {
 783    Single(Formatter),
 784    Vec(Vec<Formatter>),
 785}
 786
 787impl Default for FormatterList {
 788    fn default() -> Self {
 789        Self::Single(Formatter::default())
 790    }
 791}
 792
 793impl AsRef<[Formatter]> for FormatterList {
 794    fn as_ref(&self) -> &[Formatter] {
 795        match &self {
 796            Self::Single(single) => std::slice::from_ref(single),
 797            Self::Vec(v) => v,
 798        }
 799    }
 800}
 801
 802/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
 803#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 804#[serde(rename_all = "snake_case")]
 805pub enum Formatter {
 806    /// Format files using Zed's Prettier integration (if applicable),
 807    /// or falling back to formatting via language server.
 808    #[default]
 809    Auto,
 810    /// Format code using Zed's Prettier integration.
 811    Prettier,
 812    /// Format code using an external command.
 813    External {
 814        /// The external program to run.
 815        command: String,
 816        /// The arguments to pass to the program.
 817        arguments: Option<Vec<String>>,
 818    },
 819    /// Files should be formatted using a code action executed by language servers.
 820    CodeAction(String),
 821    /// Format code using a language server.
 822    #[serde(untagged)]
 823    LanguageServer(LanguageServerFormatterSpecifier),
 824}
 825
 826#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 827#[serde(
 828    rename_all = "snake_case",
 829    // allow specifying language servers as "language_server" or {"language_server": {"name": ...}}
 830    from = "LanguageServerVariantContent",
 831    into = "LanguageServerVariantContent"
 832)]
 833pub enum LanguageServerFormatterSpecifier {
 834    Specific {
 835        name: String,
 836    },
 837    #[default]
 838    Current,
 839}
 840
 841impl From<LanguageServerVariantContent> for LanguageServerFormatterSpecifier {
 842    fn from(value: LanguageServerVariantContent) -> Self {
 843        match value {
 844            LanguageServerVariantContent::Specific {
 845                language_server: LanguageServerSpecifierContent { name: Some(name) },
 846            } => Self::Specific { name },
 847            _ => Self::Current,
 848        }
 849    }
 850}
 851
 852impl From<LanguageServerFormatterSpecifier> for LanguageServerVariantContent {
 853    fn from(value: LanguageServerFormatterSpecifier) -> Self {
 854        match value {
 855            LanguageServerFormatterSpecifier::Specific { name } => Self::Specific {
 856                language_server: LanguageServerSpecifierContent { name: Some(name) },
 857            },
 858            LanguageServerFormatterSpecifier::Current => {
 859                Self::Current(CurrentLanguageServerContent::LanguageServer)
 860            }
 861        }
 862    }
 863}
 864
 865#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 866#[serde(rename_all = "snake_case", untagged)]
 867enum LanguageServerVariantContent {
 868    /// Format code using a specific language server.
 869    Specific {
 870        language_server: LanguageServerSpecifierContent,
 871    },
 872    /// Format code using the current language server.
 873    Current(CurrentLanguageServerContent),
 874}
 875
 876#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 877#[serde(rename_all = "snake_case")]
 878enum CurrentLanguageServerContent {
 879    #[default]
 880    LanguageServer,
 881}
 882
 883#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 884#[serde(rename_all = "snake_case")]
 885struct LanguageServerSpecifierContent {
 886    /// The name of the language server to format with
 887    name: Option<String>,
 888}
 889
 890/// The settings for indent guides.
 891#[with_fallible_options]
 892#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
 893pub struct IndentGuideSettingsContent {
 894    /// Whether to display indent guides in the editor.
 895    ///
 896    /// Default: true
 897    pub enabled: Option<bool>,
 898    /// The width of the indent guides in pixels, between 1 and 10.
 899    ///
 900    /// Default: 1
 901    pub line_width: Option<u32>,
 902    /// The width of the active indent guide in pixels, between 1 and 10.
 903    ///
 904    /// Default: 1
 905    pub active_line_width: Option<u32>,
 906    /// Determines how indent guides are colored.
 907    ///
 908    /// Default: Fixed
 909    pub coloring: Option<IndentGuideColoring>,
 910    /// Determines how indent guide backgrounds are colored.
 911    ///
 912    /// Default: Disabled
 913    pub background_coloring: Option<IndentGuideBackgroundColoring>,
 914}
 915
 916/// The task settings for a particular language.
 917#[with_fallible_options]
 918#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize, JsonSchema, MergeFrom)]
 919pub struct LanguageTaskSettingsContent {
 920    /// Extra task variables to set for a particular language.
 921    pub variables: Option<HashMap<String, String>>,
 922    pub enabled: Option<bool>,
 923    /// Use LSP tasks over Zed language extension ones.
 924    /// If no LSP tasks are returned due to error/timeout or regular execution,
 925    /// Zed language extension tasks will be used instead.
 926    ///
 927    /// Other Zed tasks will still be shown:
 928    /// * Zed task from either of the task config file
 929    /// * Zed task from history (e.g. one-off task was spawned before)
 930    pub prefer_lsp: Option<bool>,
 931}
 932
 933/// Map from language name to settings.
 934#[with_fallible_options]
 935#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
 936pub struct LanguageToSettingsMap(pub HashMap<String, LanguageSettingsContent>);
 937
 938/// Determines how indent guides are colored.
 939#[derive(
 940    Default,
 941    Debug,
 942    Copy,
 943    Clone,
 944    PartialEq,
 945    Eq,
 946    Serialize,
 947    Deserialize,
 948    JsonSchema,
 949    MergeFrom,
 950    strum::VariantArray,
 951    strum::VariantNames,
 952)]
 953#[serde(rename_all = "snake_case")]
 954pub enum IndentGuideColoring {
 955    /// Do not render any lines for indent guides.
 956    Disabled,
 957    /// Use the same color for all indentation levels.
 958    #[default]
 959    Fixed,
 960    /// Use a different color for each indentation level.
 961    IndentAware,
 962}
 963
 964/// Determines how indent guide backgrounds are colored.
 965#[derive(
 966    Default,
 967    Debug,
 968    Copy,
 969    Clone,
 970    PartialEq,
 971    Eq,
 972    Serialize,
 973    Deserialize,
 974    JsonSchema,
 975    MergeFrom,
 976    strum::VariantArray,
 977    strum::VariantNames,
 978)]
 979#[serde(rename_all = "snake_case")]
 980pub enum IndentGuideBackgroundColoring {
 981    /// Do not render any background for indent guides.
 982    #[default]
 983    Disabled,
 984    /// Use a different color for each indentation level.
 985    IndentAware,
 986}
 987
 988#[cfg(test)]
 989mod test {
 990
 991    use crate::{ParseStatus, fallible_options};
 992
 993    use super::*;
 994
 995    #[test]
 996    fn test_formatter_deserialization() {
 997        let raw_auto = "{\"formatter\": \"auto\"}";
 998        let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
 999        assert_eq!(
1000            settings.formatter,
1001            Some(FormatterList::Single(Formatter::Auto))
1002        );
1003        let raw = "{\"formatter\": \"language_server\"}";
1004        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1005        assert_eq!(
1006            settings.formatter,
1007            Some(FormatterList::Single(Formatter::LanguageServer(
1008                LanguageServerFormatterSpecifier::Current
1009            )))
1010        );
1011
1012        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
1013        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1014        assert_eq!(
1015            settings.formatter,
1016            Some(FormatterList::Vec(vec![Formatter::LanguageServer(
1017                LanguageServerFormatterSpecifier::Current
1018            )]))
1019        );
1020        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"language_server\", \"prettier\"]}";
1021        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1022        assert_eq!(
1023            settings.formatter,
1024            Some(FormatterList::Vec(vec![
1025                Formatter::LanguageServer(LanguageServerFormatterSpecifier::Current),
1026                Formatter::LanguageServer(LanguageServerFormatterSpecifier::Current),
1027                Formatter::Prettier
1028            ]))
1029        );
1030
1031        let raw = "{\"formatter\": [{\"language_server\": {\"name\": \"ruff\"}}, \"prettier\"]}";
1032        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1033        assert_eq!(
1034            settings.formatter,
1035            Some(FormatterList::Vec(vec![
1036                Formatter::LanguageServer(LanguageServerFormatterSpecifier::Specific {
1037                    name: "ruff".to_string()
1038                }),
1039                Formatter::Prettier
1040            ]))
1041        );
1042
1043        assert_eq!(
1044            serde_json::to_string(&LanguageServerFormatterSpecifier::Current).unwrap(),
1045            "\"language_server\"",
1046        );
1047    }
1048
1049    #[test]
1050    fn test_formatter_deserialization_invalid() {
1051        let raw_auto = "{\"formatter\": {}}";
1052        let (_, result) = fallible_options::parse_json::<LanguageSettingsContent>(raw_auto);
1053        assert!(matches!(result, ParseStatus::Failed { .. }));
1054    }
1055
1056    #[test]
1057    fn test_prettier_options() {
1058        let raw_prettier = r#"{"allowed": false, "tabWidth": 4, "semi": false}"#;
1059        let result = serde_json::from_str::<PrettierSettingsContent>(raw_prettier)
1060            .expect("Failed to parse prettier options");
1061        assert!(
1062            result
1063                .options
1064                .as_ref()
1065                .expect("options were flattened")
1066                .contains_key("semi")
1067        );
1068        assert!(
1069            result
1070                .options
1071                .as_ref()
1072                .expect("options were flattened")
1073                .contains_key("tabWidth")
1074        );
1075    }
1076}