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