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