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