EditorConfig - One Settings for all Editors / IDEs

    EditorConfig is a configuration file and a set of extensions, to a large number of code editors and IDEs (hereinafter simply an IDE).

    Its task is to create a single settings format, and, once and for all, solve issues like “tabs or spaces” for all IDEs and all programming languages. Such a file can be stored in the project version control system, which will allow all its developers to use the same configuration.

    Files .editorconfigcan be found in projects such as jQuery , Ruby , WordPress , and many others .

    Plugins are available for a large number of IDEs. Let's see how this works.







    Как выглядит файл EditorConfig?


    Here is an example file .editorconfigthat defines indentation rules for Python and JavaScript code:

    ## Заранее извиняюсь за отсутствие нормальной подсветки синтаксиса в этом примере и далее.
    ## Хоть "ini" и содержится в списке форматов поддерживаемых Хабром, код красивым не становится.
    ## Если кто знает, как это починить - пожалуйста напишите в личку.
    #
    # Корневой файл EditorConfig
    root = true
    # Для всех файлов используем unix-совместимые переносы строк
    [*]
    end_of_line = lf
    insert_final_newline = true
    # отступы в 4 пробела
    [*.py]
    indent_style = space
    indent_size = 4
    # Используем табы для отступов (Не указываем размер)
    [*.js]
    indent_style = tab
    # Перезависываем настройку отступов для js файлов в папке lib
    [lib/**.js]
    indent_style = space
    indent_size = 2
    # Только для файлов package.json or .travis.yml
    [{package.json,.travis.yml}]
    indent_style = space
    indent_size = 2
    


    Формат файла


    EditorConfig files use a slightly modified INIformat.
    Each .editorconfigshould be encoded UTF-8, and at the end of the lines should be either
    CRLFeither LF.

    The name of the section is a file mask, for example, [*.js]or [index.html].

    Unlike the usual .ini format, you can use [and in the section name ], which allows you to specify a list of characters, one of which should be in the specified position. For example, such constructions like this: [file[123].js]. How it works - read below.

    Each comment should be on a separate line and begin with ;or #.


    Как работает поиск файлов по маске


    * - Любое количество символов кроме разделителя пути (/)

    Example: [* .js]
    hello.js // Match
    hellojs // No match
    index.html // No match
    lib/source.js // No match


    ** - Любое количество символов

    Example: [**. Js]
    hello.js // Match
    hellojs // No match
    index.html // No match
    lib/source.js // Match


    ? - Один любой символ

    Example: [hell? .Js]
    hello.js // Match
    hell.js // No match


    [name] - Любой символ из символов содержащийся в “name”

    Example: [[abc] .js]
    a.js // Match
    b.js // Match
    abc.js // No match


    [!name] - Любой символ которого нету в “name”

    Example: [file [! 2468] .js]
    file1.js // Match
    file2.js // No match


    {s1,s2,s3} - Любая из строк разделенных запятыми

    Example: [index. {Js, html}]
    index.js // Match
    index.html // Match
    package.json // No match


    \ - Экранирование служебных символов

    Example: [\ [abc \]. Js]
    a.js // No match
    [abc].js // Match

    Настройки


    Что можно настроить?


    Editor config aims to be language independent and work in all IDEs. Unfortunately, this is not always possible, so some of the plugins do not support all settings. More details can be found on the page of each plugin in github.

    All settings are case insensitive.

    indent_style
    Values: tab, space
    Allows you to set hard or soft tabs for indentation.

    indent_size
    Values: Number
    Defines the width of the indent using soft tabs.

    tab_width
    Values: Number
    Lets you set the width of the indent using hard tabs. If not specified, will take the value from indent_size.

    end_of_line
    Values: lf, cr, crlf
    Allows you to choose what to use at the ends of lines.

    charset
    Values: latin1, utf-8, utf-8-bom, utf-16be, utf-16le
    Allows you to select the encoding for the files.
    Using utf-8-bom is not recommended

    trim_trailing_whitespace
    Values: true, false
    Removes spaces from line ends.

    insert_final_newline
    Values: true, false
    Allows you to make sure that at the end of the file there will always be a new line.

    root
    Values: true, false
    A special setting that should be at the very top of the config. If set to true, the parser will not look for other configs of the parent folders (Details below).

    Специальное значение Ignore
    Some files, such as third-party libraries or minified files, are best left untouched. In such cases, you can set a value for any setting ignore. For instance:

    # Задаем форматирование для JS и CSS
    [*.{js,css}]
    indent_style = space
    indent_size = 2
    # Но не переформатируем минифицированные JS и CSS файлы.
    [*.min.*]
    indent_style = ignore
    trim_trailing_whitespace = false
    insert_final_newline = ignore
    


    А почему так мало настроек?


    The initial task of EditorConfig is to create a minimal set of properties that works in all major IDEs.

    The task is not easy, for example, let's consider the possibility of adding a setting that would limit the line width: max_line_length
    To add this setting, you need to solve several questions:
    • Make sure all editors / IDEs support it
    • Decide whether to use hard or soft (when the line physically remains long, but looks like two) hyphenation, or let the user select it by adding one more setting (not all editors / IDEs support both types of hyphenation)
    • If you use hard porting, what to do with languages ​​where hard porting can break code? (e.g. HAML)

    At the moment, the property max_line_lengthexists, but only works in vim.


    Расширение EditorConfig


    If either a program using EditorConfig encounters an unfamiliar setting, it should ignore it. This allows you to make the format extensible and not limited to standard settings.

    There are two areas for development:

    Настройки для отдельных редакторов/IDE
    Some editors / IDEs have their own characteristics, for example, in jEdit the set of encodings is larger, therefore there is a jedit_charset setting that works only for jedit.

    Настройки для отдельных языков/расширений
    Third-party programs and plugins can extend EditorConfig and add settings that will work only for certain languages ​​or file extensions.

    For example, the npm CodePainter module , which uses EditorConfig as the configuration file, allows you to select the quotes (single or double) that will be used for strings (qoute_type), or to put spaces inside brackets (spaces_in_brackets). But all this will work only for JavaScript.

    Also, the developers have plans for a whole set of possible settings that may be used in the future, for example:

    curly_bracket_next_line
    Sets the brace to be transferred to the next line, for languages ​​where it is

    java_class_path
    Can be used by other plugins.

    language
    Allows you to set the language for the file extension. This can help when template engines, for example Jinja2, use files with the extension. The .html

    full list can be found here (eng.)

    Где хранятся эти файлы?


    When the plugin needs to calculate the configuration for the file, it will climb the file tree, from the directory with the file to the root, and load the settings from each .editorconfigfile on the way.
    The priority of settings in configs closer to the file is higher.

    For a file with this path:, the /Users/username/code/project/main.jsplugin will look for the file .editorconfigin the following places:

    /Users/username/code/project/.editorconfig
    /Users/username/code/.editorconfig
    /Users/username/.editorconfig
    /Users/.editorconfig
    /.editorconfig
    

    You can stop the search by asking root=truein one of the configs on the way.

    Such a structure allows, for example, to create .editorconfigin the user folder and thus get the default settings for all projects, and, if necessary, to rewrite these settings several levels higher.


    Как вычисляются настройки внутри файла?


    When the parser reads the file .editorconfig, it gives higher priority to the settings that are below.
    The authors created a small demo [Which at the moment, as KindDragon noted , is a bit buggy when calculating paths], where you can play around with the format and see the result


    Форматирование существующего кода


    EditorConfig plugins are designed in such a way that they change the IDE settings depending on the open file. Sometimes you have to use the undocumented or unusual features of the IDE. Because of this, formatting is only used when saving files, and if you want to use EditorConfig with existing code, you will have to use one of the tools below.

    editorconfig-tools[ github ]

    A set of tools for checking and reformatting code. It is at an early stage of development and is not yet very stable.


    ECLint[ github ]

    It is similar in functionality to editorconfig-tools, but, in addition, it can analyze existing code and generate a .editorconfigfile. Also under development.


    CodePainter[ github , npm ]

    Uses .editorconfig, but works only with JavaScript code.
    It has special settings for JS code.


    Плагины, как они работают и как их создавать?


    To help plug-in creators, a set of core components (kernels) has been created that can be used in plug-ins and take on the job of searching and parsing configuration files. At the moment there are versions in C , Java , Python , work is underway on the JavaScript version.

    The plugins themselves try to overwrite the appropriate IDE settings instead of having to do the formatting themselves.

    Unfortunately, there are still no plugins for IDEs such as Eclipse or NetBeans, their architecture does not allow you to easily change the settings.

    If there is someone among the readers who is ready to start creating plug-ins, it’s not badly written how to start (eng.)


    Для пользователей Windows


    To create a file .editorconfigin Windows Explorer, you need to create a file with a name .editorconfig.and Windows Explorer will rename it to .editorconfig.


    Ссылки и как в этом можно поучаствовать


    The EditorConfig team did an excellent job, but there are still a lot of difficulties, interesting tasks and solutions:

    • Writing and supporting plugins for lesser-known IDEs.
    • Development of kernels for plugins in other languages ​​and refinement of current ones
    • Extend functionality and add new settings
    • Refining existing code transformation solutions

    If one of the readers would be interested in participating in the project, here are some good ways to contact the developers (all in English):


    I am not in the project team, but I use .editorconfig myself and I will gladly give your suggestions and wishes - write to your personal mail.

    Also popular now: