Как настроить emmet vs code

Emmet: ускорение набора HTML-кода

Расширение Emmet позволяет значительно ускорить набор кода, путем ввода специальной комбинации символов и нажатия клавиши . Вместо этой комбинации будет вставлен фрагмент кода. Расширение не нуждается в отдельной установке, т. к. входит в состав компонентов редактора VS Code.

Вставка структуры HTML-документа

Для вставки структуры HTML-документа достаточно ввести восклицательный знак и нажать клавишу . В результате будет вставлен код:

Внутри шаблона помечены точки останова, перемещаться между которыми можно с помощью клавиши :

Три восклицательных знака позволяют вставить тег :

В структуре HTML-документа в параметре lang тега по умолчанию указывается код английского языка. Чтобы выводился код русского языка нужно в настройках редактора выполнить поиск параметра Emmet: Variables и указать значение ru для переменной lang или просто добавить следующий фрагмент кода в конец файла settings.json:

Результат после изменения значений переменных при вводе комбинации ! :

Вставка HTML-комментария

Буква c позволяет вставить HTML-комментарий:

Чтобы закомментировать блок кода, нужно предварительно его выделить, а затем в меню Правка выбрать пункт Переключить комментарий строки или нажать комбинацию клавиш + . Повторное действие удаляет комментарий. Можно также выбрать пункт Переключить комментарий блока или нажать комбинацию клавиш ++.

Теги из раздела HEAD

Комбинации для тега :

Комбинации для тега
:

Комбинации для тега script:src =>

Комбинация для тега :

Основные теги из раздела BODY

При вводе названий тегов, не имеющих отдельных комбинаций, получим открывающий и закрывающий тег:

Для некоторых тегов генерируются параметры, а также учитывается, является ли тег парным или одинарным:

Комбинации для тега :

Комбинации для вставки изображений:

В следующих случаях можно использовать сокращенные названия тегов:

Добавление текста

После вставки шаблона тега без параметров текстовый курсор будет расположен перед закрывающим тегом, что позволяет сразу начать набор текста:

Текст можно также добавить в составе комбинации внутри фигурных скобок:

Если в составе текста указать символ $ , то вместо него будет подставлен порядковый номер элемента. Создадим три абзаца и пронумеруем их:

Если указать несколько символов $ подряд, то перед номером добавятся нули:

По умолчанию нумерация элементов начинается с 1 . После символа @ можно указать другой начальный номер, например, 3 :

Для вставки текста-заполнителя следует ввести слово lorem после которого можно указать количество генерируемых слов (задавать количество слов необязательно). Создадим три абзаца и добавим в них по пять слов:

После слова lorem можно указать код языка. Сгенерируем текст на русском языке:

Не пытайтесь найти смысл во вставленном тексте. Основная цель lorem показать заказчику, как будет выглядеть дизайн сайта с произвольным текстом.

Добавление параметров тегов

Если указать только CSS-селектор стилевого класса или идентификатора, то будет создан тег

Чтобы добавить эти параметры в другой тег, предварительно указываем его название:

Если эти параметры вкладываются в блочный тег, то они добавляются к тегу :

или к другим вложенным тегам в зависимости от родительского элемента:

Для добавления произвольных параметров, их следует указывать внутри квадратных скобок. Значение параметра задается после символа = внутри одинарных или двойных кавычек. Если значение не содержит пробела, то кавычки можно не указывать. Если параметр не содержит значения, то достаточно вставить только название параметра:

Формы и элементы управления

Для вставки формы и элементов управления используются следующие комбинации символов:

Таблицы

Для быстрой вставки таблиц, строк и ячеек можно использовать такие комбинации:

Списки

Для быстрой вставки списков можно использовать следующие комбинации:

Вставка сразу нескольких тегов

Чтобы вставить несколько одинаковых тегов друг за другом, следует добавить символ * , после которого указать количество повторов. Вставим три абзаца и пронумеруем их:

Символ > означает, что нужно выполнить вложение внутрь тега. В предыдущем примере мы вкладывали текст. Вложим пункт внутрь списка:

Символ + добавляет элемент после текущего элемента:

Как видно из примера, можно комбинировать символы * , > и + , создавая сложные структуры. В последнем подвыражении мы вставляли пункты внутрь списка. Если попробовать в конец выражения вставить символ + и тег, то это тег будет вставлен после тега
. Как же нам вставить тег после списка? Чтобы переместиться выше по дереву на один уровень нужно указать символ ^ :

Читайте также:  Как скопировать данные с андроида если не работает экран

Чтобы переместиться на несколько уровней выше, следует символ ^ указать несколько раз:

Можно также ограничить вложение, добавив группу внутрь круглых скобок:


Подробное описание руководства по редактору Visual Studio Code (PDF)

Помощь сайту

ПАО Сбербанк:
Счет: 40817810855006152256
Реквизиты банка:
Наименование: СЕВЕРО-ЗАПАДНЫЙ БАНК ПАО СБЕРБАНК
Корреспондентский счет: 30101810500000000653
БИК: 044030653
КПП: 784243001
ОКПО: 09171401
ОКОНХ: 96130
Скриншот реквизитов

Источник

Как пользоваться плагином Emmet (VS Code)

Для VS Code не нужно устанавливать отдельный плагин Emmet, разработчики данного редактора обоснованно посчитали, что без Emmet-а уже никак не обойтись разработчикам и встроили его в редактор. Однако не все новички умеют пользоваться плагином Emmet, тем самым воруют сами у себя драгоценное время и превращают процесс написания кода в скучную рутину. Эта статья будет полезна тем, кто много пишет кода, но все еще не использует Emmet в работе.

Как пользоваться Emmet верстальщику

Emmet позволяет быстро набирать код, благодаря использованию большого количества сокращений (аббревиатур). Вы не набираете ручками HTML/CSS код целиком, а прописываете их в сокращенном виде и после нажатия определенных комбинаций клавиш, код полностью разворачивается.

Emmet: HTML сокращения

Создать базовую структуру HTML документа

Если набрать в редакторе «!» и нажать Tab, то Emmet вставит скелет HTML документа.

Подключение CSS файла

Для подключения CSS файла к HTML документу, достаточно написать link и нажать Tab, чтобы Emmet вставил весь тег.

Развернуть ссылку

Меня всегда бесило прописывание в ссылке http и вот наконец-то пришел конец моим мучениям a:link.

Добавить тег

Чтобы добавить тег, нужно просто написать название тега и нажать Tab.

Для добавления тега с классом, вводите только название класса и точку .box.

Если нужен какой-то другой тег с классом, то соответственно пишем header.top

Развернуть список

С Emmet стало проще разворачивать списки, пользуясь формулой ul>li*5.

Генерация текста lorem

Невероятно просто стало генерировать текст с любым количеством абзацев p*3>lorem.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae illum placeat quisquam, eaque quia vero neque, itaque ducimus cum quasi doloribus aperiam eos dignissimos, eum labore esse. Eligendi, veritatis nulla!

Autem maxime unde iusto sunt atque deleniti perspiciatis id praesentium. Necessitatibus sequi non delectus! Maxime voluptates excepturi ducimus nesciunt at, dolor iste molestias itaque sed esse nisi perferendis sequi! Fugiat?

Suscipit molestias odit impedit voluptatem laborum a est, iure dolorum autem? Accusamus, esse pariatur ipsam eum consequatur error, accusantium corporis magni a ipsa blanditiis neque impedit porro, alias deserunt voluptatibus?

Emmet: CSS сокращения

Аббревиатуры CSS сокращений исходят из названия самих свойств, поэтому здесь все логично. Напишем стили вместе с Emmet для селектора header. Вам не нужно ничего заучивать, плагин Emmet умеет давать подсказки.

Как видите использование Emmet в разы ускоряет написание кода, при условии что вы хорошо знаете HTML теги и CSS свойства. Кроме того прописывание всего селектора (свойство: значение), малоинтересное занятие. Если вы ещё не используете Emmet, то я настоятельно рекомендую не отказываться от такой замечательной возможности.

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Порекомендуйте эту статью друзьям:

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

Она выглядит вот так:

  • BB-код ссылки для форумов (например, можете поставить её в подписи):
  • Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2021 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Emmet in Visual Studio Code

    Support for Emmet snippets and expansion is built right into Visual Studio Code, no extension required. Emmet 2.0 has support for the majority of the Emmet Actions including expanding Emmet abbreviations and snippets.

    How to expand Emmet abbreviations and snippets

    Emmet abbreviation and snippet expansions are enabled by default in html , haml , pug , slim , jsx , xml , xsl , css , scss , sass , less and stylus files, as well as any language that inherits from any of the above like handlebars and php .

    Читайте также:  Человек головой работает не то что ты

    When you start typing an Emmet abbreviation, you will see the abbreviation displayed in the suggestion list. If you have the suggestion documentation fly-out open, you will see a preview of the expansion as you type. If you are in a stylesheet file, the expanded abbreviation shows up in the suggestion list sorted among the other CSS suggestions.

    Using Tab for Emmet expansions

    If you want to use the Tab key for expanding the Emmet abbreviations, add the following setting:

    This setting allows using the Tab key for indentation when text is not an Emmet abbreviation.

    Emmet when quickSuggestions are disabled

    If you have disabled the editor.quickSuggestions setting, you won’t see suggestions as you type. You can still trigger suggestions manually by pressing ⌃Space (Windows, Linux Ctrl+Space ) and see the preview.

    Disable Emmet in suggestions

    If you don’t want to see Emmet abbreviations in suggestions at all, then use the following setting:

    You can still use the command Emmet: Expand Abbreviation to expand your abbreviations. You can also bind any keyboard shortcut to the command id editor.emmet.action.expandAbbreviation as well.

    Emmet suggestion ordering

    To ensure Emmet suggestions are always on top in the suggestion list, add the following settings:

    Emmet abbreviations in other file types

    To enable the Emmet abbreviation expansion in file types where it is not available by default, use the emmet.includeLanguages setting. Make sure to use language identifiers for both sides of the mapping, with the right side being the language identifier of an Emmet supported language (see the list above).

    Emmet has no knowledge of these new languages, and so there might be Emmet suggestions showing up in non HTML/CSS contexts. To avoid this, you can use the following setting.

    Note: If you used emmet.syntaxProfiles previously to map new file types, from VS Code 1.15 onwards you should use the setting emmet.includeLanguages instead. emmet.syntaxProfiles is meant for customizing the final output only.

    Emmet with multi-cursors

    You can use most of the Emmet actions with multi-cursors as well:

    Using filters

    Filters are special post-processors that modify the expanded abbreviation before it is output to the editor. There are 2 ways to use filters; either globally through the emmet.syntaxProfiles setting or directly in the current abbreviation.

    Below is an example of the first approach using the emmet.syntaxProfiles setting to apply the bem filter for all the abbreviations in HTML files:

    To provide a filter for just the current abbreviation, append the filter to your abbreviation. For example, div#page|c will apply the comment filter to the div#page abbreviation.

    BEM filter (bem)

    If you use the Block Element Modifier (BEM) way of writing HTML, then bem filters are very handy for you to use. To learn more about how to use bem filters, read BEM filter in Emmet.

    You can customize this filter by using the bem.elementSeparator and bem.modifierSeparator preferences as documented in Emmet Preferences.

    Comment filter (c)

    This filter adds comments around important tags. By default, «important tags» are those tags with id and/or class attribute.

    For example div>div#page>p.title+p|c will be expanded to:

    You can customize this filter by using the filter.commentTrigger , filter.commentAfter and filter.commentBefore preferences as documented in Emmet Preferences.

    The format for the filter.commentAfter preference is different in VS Code Emmet 2.0.

    For example, instead of:

    in VS Code, you would use a simpler:

    Trim filter (t)

    This filter is applicable only when providing abbreviations for the Emmet: Wrap with Abbreviation command. It removes line markers from wrapped lines.

    Using custom Emmet snippets

    Custom Emmet snippets need to be defined in a json file named snippets.json . The emmet.extensionsPath setting should have the path to the directory containing this file.

    Below is an example for the contents of this snippets.json file.

    Authoring of Custom Snippets in Emmet 2.0 via the snippets.json file differs from the old way of doing the same in a few ways:

    Topic Old Emmet Emmet 2.0
    Snippets vs Abbreviations Supports both in 2 separate properties called snippets and abbreviations The 2 have been combined into a single property called snippets. See default HTML snippets and CSS snippets
    CSS snippet names Can contain : Do not use : when defining snippet names. It is used to separate property name and value when Emmet tries to fuzzy match the given abbreviation to one of the snippets.
    CSS snippet values Can end with ; Do not add ; at end of snippet value. Emmet will add the trailing ; based on the file type (css/less/scss vs sass/stylus) or the emmet preference set for css.propertyEnd , sass.propertyEnd , stylus.propertyEnd
    Cursor location $ or | can be used Use only textmate syntax like $ <1>for tab stops and cursor locations

    HTML Emmet snippets

    HTML custom snippets are applicable to all other markup flavors like haml or pug . When snippet value is an abbreviation and not actual HTML, the appropriate transformations can be applied to get the right output as per the language type.

    For example, for an unordered list with a list item, if your snippet value is ul>li , you can use the same snippet in html , haml , pug or slim , but if your snippet value is , then it will work only in html files.

    If you want a snippet for plain text, then surround the text with <> .

    CSS Emmet snippets

    Values for CSS Emmet snippets should be a complete property name and value pair.

    CSS custom snippets are applicable to all other stylesheet flavors like scss , less or sass . Therefore, don’t include a trailing ; at the end of the snippet value. Emmet will add it as needed based on whether the language requires it.

    Do not use : in the snippet name. : is used to separate property name and value when Emmet tries to fuzzy match the abbreviation to one of the snippets.

    Tab stops and cursors in custom snippets

    The syntax for tab stops in custom Emmet snippets follows the Textmate snippets syntax.

    • Use $ <1>, $ <2>for tab stops and $ <1:placeholder>for tab stops with placeholders.
    • Previously, | or $ was used to denote the cursor location in the custom Emmet snippet. This is no longer supported. Use $ <1>instead.

    Emmet configuration

    Below are Emmet settings that you can use to customize your Emmet experience in VS Code.

    Use this setting to add mapping between the language of your choice and one of the Emmet supported languages to enable Emmet in the former using the syntax of the latter. Make sure to use language IDs for both sides of the mapping.

    If there is a language where you do not want to see Emmet expansions, add it in this setting which takes an array of language ID strings.

    See Emmet Customization of output profile to learn how you can customize the output of your HTML abbreviations.

    Customize variables used by Emmet snippets.

    Controls the Emmet suggestions that show up in the suggestion/completion list.

    Setting Value Description
    never Never show Emmet abbreviations in the suggestion list for any language.
    inMarkupAndStylesheetFilesOnly Show Emmet suggestions only for languages that are purely markup and stylesheet based (‘html’, ‘pug’, ‘slim’, ‘haml’, ‘xml’, ‘xsl’, ‘css’, ‘scss’, ‘sass’, ‘less’, ‘stylus’).
    always Show Emmet suggestions in all Emmet supported modes as well as the languages that have a mapping in the emmet.includeLanguages setting.

    Note: In the always mode, the new Emmet implementation is not context aware. For example, if you are editing a JavaScript React file, you will get Emmet suggestions not only when writing markup but also while writing JavaScript.

    Shows possible emmet abbreviations as suggestions. It is true by default.

    For example, when you type li , you get suggestions for all emmet snippets starting with li like link , link:css , link:favicon etc. This is helpful in learning Emmet snippets that you never knew existed unless you knew the Emmet cheatsheet by heart.

    Not applicable in stylesheets or when emmet.showExpandedAbbreviation is set to never .

    Provide the location of the directory that houses the snippets.json file which in turn has your custom snippets.

    Set this to true to enable expanding Emmet abbreviations with Tab key. We use this setting to provide the appropriate fallback to provide indentation when there is no abbreviation to expand.

    If set to true , then Emmet suggestions will be grouped along with other snippets allowing you to order them as per editor.snippetSuggestions setting. Set this to true and editor.snippetSuggestions to top , to ensure that Emmet suggestions always show up on top among other suggestions.

    You can use this setting to customize Emmet as documented in Emmet Preferences. The below customizations are currently supported:

    Источник

    Оцените статью