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