1234 lines · 43.2 KB · Rust
RawDownload
//! Provides `language`-related settings. use crate::{File, Language, LanguageName, LanguageServerName};use anyhow::Result;use collections::{HashMap, HashSet};use core::slice;use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};use gpui::AppContext;use itertools::{Either, Itertools};use schemars::{    schema::{InstanceType, ObjectValidation, Schema, SchemaObject, SingleOrVec},    JsonSchema,};use serde::{    de::{self, IntoDeserializer, MapAccess, SeqAccess, Visitor},    Deserialize, Deserializer, Serialize,};use serde_json::Value;use settings::{add_references_to_properties, Settings, SettingsLocation, SettingsSources};use std::{num::NonZeroU32, path::Path, sync::Arc};use util::serde::default_true; /// Initializes the language settings.pub fn init(cx: &mut AppContext) {    AllLanguageSettings::register(cx);} /// Returns the settings for the specified language from the provided file.pub fn language_settings<'a>(    language: Option<&Arc<Language>>,    file: Option<&Arc<dyn File>>,    cx: &'a AppContext,) -> &'a LanguageSettings {    let language_name = language.map(|l| l.name());    all_language_settings(file, cx).language(language_name.as_ref())} /// Returns the settings for all languages from the provided file.pub fn all_language_settings<'a>(    file: Option<&Arc<dyn File>>,    cx: &'a AppContext,) -> &'a AllLanguageSettings {    let location = file.map(|f| SettingsLocation {        worktree_id: f.worktree_id(cx),        path: f.path().as_ref(),    });    AllLanguageSettings::get(location, cx)} /// The settings for all languages.#[derive(Debug, Clone)]pub struct AllLanguageSettings {    /// The inline completion settings.    pub inline_completions: InlineCompletionSettings,    defaults: LanguageSettings,    languages: HashMap<LanguageName, LanguageSettings>,    pub(crate) file_types: HashMap<Arc<str>, GlobSet>,} /// The settings for a particular language.#[derive(Debug, Clone, Deserialize)]pub struct LanguageSettings {    /// How many columns a tab should occupy.    pub tab_size: NonZeroU32,    /// Whether to indent lines using tab characters, as opposed to multiple    /// spaces.    pub hard_tabs: bool,    /// How to soft-wrap long lines of text.    pub soft_wrap: SoftWrap,    /// The column at which to soft-wrap lines, for buffers where soft-wrap    /// is enabled.    pub preferred_line_length: u32,    // Whether to show wrap guides (vertical rulers) in the editor.    // Setting this to true will show a guide at the 'preferred_line_length' value    // if softwrap is set to 'preferred_line_length', and will show any    // additional guides as specified by the 'wrap_guides' setting.    pub show_wrap_guides: bool,    /// Character counts at which to show wrap guides (vertical rulers) in the editor.    pub wrap_guides: Vec<usize>,    /// Indent guide related settings.    pub indent_guides: IndentGuideSettings,    /// Whether or not to perform a buffer format before saving.    pub format_on_save: FormatOnSave,    /// Whether or not to remove any trailing whitespace from lines of a buffer    /// before saving it.    pub remove_trailing_whitespace_on_save: bool,    /// Whether or not to ensure there's a single newline at the end of a buffer    /// when saving it.    pub ensure_final_newline_on_save: bool,    /// How to perform a buffer format.    pub formatter: SelectedFormatter,    /// Zed's Prettier integration settings.    pub prettier: PrettierSettings,    /// Whether to use language servers to provide code intelligence.    pub enable_language_server: bool,    /// The list of language servers to use (or disable) for this language.    ///    /// This array should consist of language server IDs, as well as the following    /// special tokens:    /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.    /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.    pub language_servers: Vec<Arc<str>>,    /// Controls whether inline completions are shown immediately (true)    /// or manually by triggering `editor::ShowInlineCompletion` (false).    pub show_inline_completions: bool,    /// Whether to show tabs and spaces in the editor.    pub show_whitespaces: ShowWhitespaceSetting,    /// Whether to start a new line with a comment when a previous line is a comment as well.    pub extend_comment_on_newline: bool,    /// Inlay hint related settings.    pub inlay_hints: InlayHintSettings,    /// Whether to automatically close brackets.    pub use_autoclose: bool,    /// Whether to automatically surround text with brackets.    pub use_auto_surround: bool,    // Controls how the editor handles the autoclosed characters.    pub always_treat_brackets_as_autoclosed: bool,    /// Which code actions to run on save    pub code_actions_on_format: HashMap<String, bool>,    /// Whether to perform linked edits    pub linked_edits: bool,    /// Task configuration for this language.    pub tasks: LanguageTaskConfig,} impl LanguageSettings {    /// A token representing the rest of the available language servers.    const REST_OF_LANGUAGE_SERVERS: &'static str = "...";     /// Returns the customized list of language servers from the list of    /// available language servers.    pub fn customized_language_servers(        &self,        available_language_servers: &[LanguageServerName],    ) -> Vec<LanguageServerName> {        Self::resolve_language_servers(&self.language_servers, available_language_servers)    }     pub(crate) fn resolve_language_servers(        configured_language_servers: &[Arc<str>],        available_language_servers: &[LanguageServerName],    ) -> Vec<LanguageServerName> {        let (disabled_language_servers, enabled_language_servers): (Vec<Arc<str>>, Vec<Arc<str>>) =            configured_language_servers.iter().partition_map(                |language_server| match language_server.strip_prefix('!') {                    Some(disabled) => Either::Left(disabled.into()),                    None => Either::Right(language_server.clone()),                },            );         let rest = available_language_servers            .iter()            .filter(|&available_language_server| {                !disabled_language_servers.contains(&available_language_server.0)                    && !enabled_language_servers.contains(&available_language_server.0)            })            .cloned()            .collect::<Vec<_>>();         enabled_language_servers            .into_iter()            .flat_map(|language_server| {                if language_server.as_ref() == Self::REST_OF_LANGUAGE_SERVERS {                    rest.clone()                } else {                    vec![LanguageServerName(language_server.clone())]                }            })            .collect::<Vec<_>>()    }} /// The provider that supplies inline completions.#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]#[serde(rename_all = "snake_case")]pub enum InlineCompletionProvider {    None,    #[default]    Copilot,    Supermaven,} /// The settings for inline completions, such as [GitHub Copilot](https://github.com/features/copilot)/// or [Supermaven](https://supermaven.com).#[derive(Clone, Debug, Default)]pub struct InlineCompletionSettings {    /// The provider that supplies inline completions.    pub provider: InlineCompletionProvider,    /// A list of globs representing files that inline completions should be disabled for.    pub disabled_globs: Vec<GlobMatcher>,} /// The settings for all languages.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]pub struct AllLanguageSettingsContent {    /// The settings for enabling/disabling features.    #[serde(default)]    pub features: Option<FeaturesContent>,    /// The inline completion settings.    #[serde(default)]    pub inline_completions: Option<InlineCompletionSettingsContent>,    /// The default language settings.    #[serde(flatten)]    pub defaults: LanguageSettingsContent,    /// The settings for individual languages.    #[serde(default)]    pub languages: HashMap<LanguageName, LanguageSettingsContent>,    /// Settings for associating file extensions and filenames    /// with languages.    #[serde(default)]    pub file_types: HashMap<Arc<str>, Vec<String>>,} /// The settings for a particular language.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]pub struct LanguageSettingsContent {    /// How many columns a tab should occupy.    ///    /// Default: 4    #[serde(default)]    pub tab_size: Option<NonZeroU32>,    /// Whether to indent lines using tab characters, as opposed to multiple    /// spaces.    ///    /// Default: false    #[serde(default)]    pub hard_tabs: Option<bool>,    /// How to soft-wrap long lines of text.    ///    /// Default: none    #[serde(default)]    pub soft_wrap: Option<SoftWrap>,    /// The column at which to soft-wrap lines, for buffers where soft-wrap    /// is enabled.    ///    /// Default: 80    #[serde(default)]    pub preferred_line_length: Option<u32>,    /// Whether to show wrap guides in the editor. Setting this to true will    /// show a guide at the 'preferred_line_length' value if softwrap is set to    /// 'preferred_line_length', and will show any additional guides as specified    /// by the 'wrap_guides' setting.    ///    /// Default: true    #[serde(default)]    pub show_wrap_guides: Option<bool>,    /// Character counts at which to show wrap guides in the editor.    ///    /// Default: []    #[serde(default)]    pub wrap_guides: Option<Vec<usize>>,    /// Indent guide related settings.    #[serde(default)]    pub indent_guides: Option<IndentGuideSettings>,    /// Whether or not to perform a buffer format before saving.    ///    /// Default: on    #[serde(default)]    pub format_on_save: Option<FormatOnSave>,    /// Whether or not to remove any trailing whitespace from lines of a buffer    /// before saving it.    ///    /// Default: true    #[serde(default)]    pub remove_trailing_whitespace_on_save: Option<bool>,    /// Whether or not to ensure there's a single newline at the end of a buffer    /// when saving it.    ///    /// Default: true    #[serde(default)]    pub ensure_final_newline_on_save: Option<bool>,    /// How to perform a buffer format.    ///    /// Default: auto    #[serde(default)]    pub formatter: Option<SelectedFormatter>,    /// Zed's Prettier integration settings.    /// Allows to enable/disable formatting with Prettier    /// and configure default Prettier, used when no project-level Prettier installation is found.    ///    /// Default: off    #[serde(default)]    pub prettier: Option<PrettierSettings>,    /// Whether to use language servers to provide code intelligence.    ///    /// Default: true    #[serde(default)]    pub enable_language_server: Option<bool>,    /// The list of language servers to use (or disable) for this language.    ///    /// This array should consist of language server IDs, as well as the following    /// special tokens:    /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.    /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.    ///    /// Default: ["..."]    #[serde(default)]    pub language_servers: Option<Vec<Arc<str>>>,    /// Controls whether inline completions are shown immediately (true)    /// or manually by triggering `editor::ShowInlineCompletion` (false).    ///    /// Default: true    #[serde(default)]    pub show_inline_completions: Option<bool>,    /// Whether to show tabs and spaces in the editor.    #[serde(default)]    pub show_whitespaces: Option<ShowWhitespaceSetting>,    /// Whether to start a new line with a comment when a previous line is a comment as well.    ///    /// Default: true    #[serde(default)]    pub extend_comment_on_newline: Option<bool>,    /// Inlay hint related settings.    #[serde(default)]    pub inlay_hints: Option<InlayHintSettings>,    /// Whether to automatically type closing characters for you. For example,    /// when you type (, Zed will automatically add a closing ) at the correct position.    ///    /// Default: true    pub use_autoclose: Option<bool>,    /// Whether to automatically surround text with characters for you. For example,    /// when you select text and type (, Zed will automatically surround text with ().    ///    /// Default: true    pub use_auto_surround: Option<bool>,    // Controls how the editor handles the autoclosed characters.    // When set to `false`(default), skipping over and auto-removing of the closing characters    // happen only for auto-inserted characters.    // Otherwise(when `true`), the closing characters are always skipped over and auto-removed    // no matter how they were inserted.    ///    /// Default: false    pub always_treat_brackets_as_autoclosed: Option<bool>,    /// Which code actions to run on save after the formatter.    /// These are not run if formatting is off.    ///    /// Default: {} (or {"source.organizeImports": true} for Go).    pub code_actions_on_format: Option<HashMap<String, bool>>,    /// Whether to perform linked edits of associated ranges, if the language server supports it.    /// For example, when editing opening <html> tag, the contents of the closing </html> tag will be edited as well.    ///    /// Default: true    pub linked_edits: Option<bool>,    /// Task configuration for this language.    ///    /// Default: {}    pub tasks: Option<LanguageTaskConfig>,} /// The contents of the inline completion settings.#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)]pub struct InlineCompletionSettingsContent {    /// A list of globs representing files that inline completions should be disabled for.    #[serde(default)]    pub disabled_globs: Option<Vec<String>>,} /// The settings for enabling/disabling features.#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema)]#[serde(rename_all = "snake_case")]pub struct FeaturesContent {    /// Whether the GitHub Copilot feature is enabled.    pub copilot: Option<bool>,    /// Determines which inline completion provider to use.    pub inline_completion_provider: Option<InlineCompletionProvider>,} /// Controls the soft-wrapping behavior in the editor.#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]#[serde(rename_all = "snake_case")]pub enum SoftWrap {    /// Do not soft wrap.    None,    /// Prefer a single line generally, unless an overly long line is encountered.    PreferLine,    /// Soft wrap lines that exceed the editor width    EditorWidth,    /// Soft wrap lines at the preferred line length    PreferredLineLength,    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller)    Bounded,} /// Controls the behavior of formatting files when they are saved.#[derive(Debug, Clone, PartialEq, Eq)]pub enum FormatOnSave {    /// Files should be formatted on save.    On,    /// Files should not be formatted on save.    Off,    List(FormatterList),} impl JsonSchema for FormatOnSave {    fn schema_name() -> String {        "OnSaveFormatter".into()    }     fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> Schema {        let mut schema = SchemaObject::default();        let formatter_schema = Formatter::json_schema(generator);        schema.instance_type = Some(            vec![                InstanceType::Object,                InstanceType::String,                InstanceType::Array,            ]            .into(),        );         let valid_raw_values = SchemaObject {            enum_values: Some(vec![                Value::String("on".into()),                Value::String("off".into()),                Value::String("prettier".into()),                Value::String("language_server".into()),            ]),            ..Default::default()        };        let mut nested_values = SchemaObject::default();         nested_values.array().items = Some(formatter_schema.clone().into());         schema.subschemas().any_of = Some(vec![            nested_values.into(),            valid_raw_values.into(),            formatter_schema,        ]);        schema.into()    }} impl Serialize for FormatOnSave {    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>    where        S: serde::Serializer,    {        match self {            Self::On => serializer.serialize_str("on"),            Self::Off => serializer.serialize_str("off"),            Self::List(list) => list.serialize(serializer),        }    }} impl<'de> Deserialize<'de> for FormatOnSave {    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>    where        D: Deserializer<'de>,    {        struct FormatDeserializer;         impl<'d> Visitor<'d> for FormatDeserializer {            type Value = FormatOnSave;             fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {                formatter.write_str("a valid on-save formatter kind")            }            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>            where                E: serde::de::Error,            {                if v == "on" {                    Ok(Self::Value::On)                } else if v == "off" {                    Ok(Self::Value::Off)                } else if v == "language_server" {                    Ok(Self::Value::List(FormatterList(                        Formatter::LanguageServer { name: None }.into(),                    )))                } else {                    let ret: Result<FormatterList, _> =                        Deserialize::deserialize(v.into_deserializer());                    ret.map(Self::Value::List)                }            }            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>            where                A: MapAccess<'d>,            {                let ret: Result<FormatterList, _> =                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));                ret.map(Self::Value::List)            }            fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>            where                A: SeqAccess<'d>,            {                let ret: Result<FormatterList, _> =                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));                ret.map(Self::Value::List)            }        }        deserializer.deserialize_any(FormatDeserializer)    }} /// Controls how whitespace should be displayedin the editor.#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]#[serde(rename_all = "snake_case")]

Lines 1–500 of 1234.