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