Sublime text 2 emmet установить
После нескольких месяцев активной разработки, я хотел бы объявить о новой версии плагина Emmet для Sublime Text!
tl;dr: новый Emmet намного быстрее, меньше и лучше. Он не выламывает клавишу Tab, обеспечивает интерактивный предварительный просмотр расширенной аббревиатуры и имеет улучшенную поддержку JSX. Новый плагин находится в стадии бета-версии и должен быть установлен из внешнего репозитория. И если вам нравится Emmet, пожалуйста, поддержите его через Спонсоров GitHub: он помогает мне поддерживать проект дальше.
8 лет назад была выпущена первая версия Emmet, ставшая одним из самых скачиваемых пакетов для редактора Sublime Text. В те дни, когда Эммет был новеньким, я старался поддерживать как можно больше редакторов. Поскольку большинство редакторов расширено с помощью JavaScript, я хотел повторно использовать существующую JS-кодовую базу для Sublime Text, которая расширена с помощью Python.
Хотя это решение позволило мне реализовать плагин Sublime Text довольно быстро и (теоретически) облегчить дальнейшую поддержку плагина, у него было слишком много недостатков:
1) он требовал отдельной загрузки большого двоичного файла PyV8;
2) запуск JS внутри Python привел к значительному снижению производительности и стабильности;
3) это не позволяет глубже интегрироваться с возможностями Sublime Text.
Новая кодовая база Emmet - это полное переосмысление архитектуры и того, как пользователи должны взаимодействовать с расширениями.
Почти все пользователи хотят расширить аббревиатуру Emmet с помощью клавиши Tab, как и обычные фрагменты. Проблема заключается в том, что простая привязка клавиши Tab к действию Expand Emmet Abbreviation (Расширение аббревиатуры Эммета) не позволяет пользователям использовать нативные фрагменты. Более того, это разбивает другие важные функции редактора, такие как отступ, переход к следующему табулятору и т.д.
В плагине Emmet 2 используется новая парадигма, называемая захватом аббревиатуры. Когда вы начинаете вводить слово (в принципе, любое слово может быть аббревиатурой!), Emmet начинает его отслеживать (отображается как тонкое подчеркивание). Таким образом, подчеркнутое слово означает, что Emmet может расширить его как аббревиатуру: просто нажмите Tab, чтобы сделать это!
Если вы просто вводите обычный текст, то, скорее всего, вы введете некоторую некорректную аббревиатуру, например, пробел или запятую: при этом в конце захваченной аббревиатуры она будет автоматически сброшена, как будто ничего не случилось. Или просто нажмите клавишу Esc, чтобы принудительно сбросить аббревиатуру, и используйте клавишу Tab, чтобы развернуть фрагменты или вставить отступ.
Но самое интересное заключается в том, что когда аббревиатура становится сложной (содержит более одного элемента), вы увидите расширенный просмотр аббревиатуры, который обновляется в реальном времени при редактировании аббревиатуры:
Помните, что Emmet расширяет аббревиатуру по клавише Tab только в том случае, если она захвачена (имеет едва уловимое подчёркивание)! В противном случае клавиша Tab действует нормально.
Emmet также выступает в качестве провайдера автозавершения: если у вас уже есть аббревиатура в редакторе и вы хотите ее развернуть, переместите каретту в конце аббревиатуры и вызовите всплывающее окно автозавершения (по умолчанию Ctrl-Space):
Обратите внимание, что по умолчанию Sublime Text вставляет единичное завершение (например, немедленно расширяет аббревиатуру). Если вы хотите захватить аббревиатуру и продолжить ее редактирование с помощью интерактивного предварительного просмотра, запустите новый Emmet: Действие "Захват аббревиатуры".
Убедитесь, что синтаксис вашего документа в Sublime Text установлен на JSX, а не на JavaScript.
Поскольку любое слово может быть аббревиатурой Эммета, захват его таким же образом, как и в HTML, вызовет слишком много отвлекающих моментов при написании обычного JavaScript. Чтобы решить эту проблему, в JSX необходимо явно префиксовать аббревиатуру с < символом:
Кроме того, у Эммета есть некоторые внутренние улучшения для JSX:
Обнаружение нотации модуля на верблюжьей упряжке: Foo.Bar будет расширен до вместо ;
Атрибуты выражения: div[class=].
В CSS, Sublime Text использует немного другое поведение автозавершения: он отображает завершения по умолчанию и не перезаполняет список завершений по мере того, как вы набираете далее, что не позволяет Emmet построить правильное динамическое завершение. Чтобы преодолеть эту проблему, Emmet отображает предварительный просмотр аббревиатуры сразу после caret в качестве phantom:
Еще одна новинка Emmet 2 - встроенный предварительный просмотр открывающего тега. При перемещении каретты внутри названия закрывающего тега, а его соответствие открывающему тегу не видно на экране, вы увидите встроенный просмотр тега:
Нажмите на этот предварительный просмотр, чтобы перейти к открытию тега.
Все остальные действия, такие как "Обертка с аббревиатурой", "Баланс", "Выделить элемент" и т.д. также поддерживаются, но не имеют привязки клавиш по умолчанию: это создало слишком много проблем для новых пользователей, когда Emmet переопределяет действия из других плагинов. Вы должны либо вызывать эти действия через командную палитру, либо создавать свои собственные сочетания клавиш (список доступных действий см. в файле Default.sublime-commands).
Последний плагин Sublime Text предоставит веб-интерфейс для тонкой настройки опций Emmet и привязки клавиш.
Пожалуйста, сначала удалите старый плагин Emmet, иначе новый плагин не будет работать.
Новый плагин Emmet находится в стадии бета-версии и вскоре заменит старый плагин в Package Control. Если вы хотите попробовать новый плагин, вам необходимо установить его из внешнего репозитория:
В Sublime Text, откройте командную строку, найдите и запустите Package Control: Add Repository command: Add Repository.
Из командной строки, запустите управление пакетами: Установить команду пакета.
В списке открытых пакетов найдите пакет Emmet2 и установите его.
Если на последнем шаге вы не можете найти пакет Emmet2 или установленный пакет не работает, перезапустите Sublime Text и повторите попытку.
Emmet - бесплатный проект с открытым исходным кодом, разработанный одним человеком в свободное от работы время. Мне очень сложно поддерживать проект такого масштаба и популярности, но при этом платить по счетам.
Если вы считаете Emmet полезным для вас или вашей компании, или вы хотите поддержать нового редактора или будущее, пожалуйста, рассмотрите возможность спонсорства проекта через Спонсоров GitHub! Каждое пожертвование заставляет меня меньше беспокоиться о деньгах и концентрироваться на возможностях и улучшениях Emmet.
Еще больше интересной информации по программированию вы можете найти в нашем Телеграмм-канале по ссылке:
Emmet 2 for Sublime Text editor
This is the next version of Emmet plugin with greatly improved developer experience and new features. Read below for more details. Plugin is currently in beta stage and may contain bugs.
Emmet is a web-developer’s toolkit for boosting HTML & CSS code writing.
With Emmet, you can type expressions (abbreviations) similar to CSS selectors and convert them into code fragment with a single keystroke. For example, this abbreviation:
. can be expanded into:
- From Command Palette , run Package Control: Install Package command.
- In opened packages list, find Emmet package and install it
If you’re unable to find Emmet package on last step or installed package doesn’t work as expected, restart Sublime Text and try again
If you used previous version of Emmet plugin, you already know how to expand abbreviations: type something like ul>li.items*4 and hit Tab or Ctrl-E . While this approach generally works, it has lots of downsides:
- Tab key hijacking: Emmet binds Tab key for expanding abbreviations so user is unable to insert native Sublime Text snippet or put tab right after word since almost every word can be abbreviation for Emmet.
- No preview of expanded abbreviations: writing complex abbreviations becomes trial and error with expand/undo/expand actions.
- Unpredictable result: it’s not possible to determine what happens when you hit Tab key, it will either expand abbreviation, insert native snippet or just output tab character.
In this plugin, abbreviation expander acts as autocomplete provider and automatically captures abbreviation as you type.
When you start typing in Emmet-supported context (HTML, CSS, Slim etc.) Emmet detects if you’re typing something similar to abbreviation and adds underline which indicates captured abbreviation. When captured abbreviation becomes complex (e.g. contains attributes or multiple elements), you’ll see a preview of expanded abbreviation every time caret is inside it. Hit Tab key inside captured abbreviation to expand it, hit Esc to remove mark from abbreviation so you can use Tab for expanding native ST snippets or insert tab character.
If you already have an abbreviation in document and you want to expand it, move caret to the end of abbreviation and invoke autocomplete ( Ctrl+Space by default) to capture abbreviation:
Make sure your document syntax is set to JSX, not JavaScript
Writing Emmet abbreviations in JSX is a bit tricky: in most cases you’d expect Tab key to expand native Sublime Text snippets and use Emmet for specific context only. So a default abbreviation capturing for every variable or snippet would annoy you.
To solve this problem, Emmet uses prefixed abbreviations in JSX: it will capture and expand abbreviation only if it’s prefixed with a specific symbol(s). By default, it’s a < character:
Emmet detects camel-cased module notation in JSX: Foo.Bar will be expanded as instead of . Expression attributes are supported as well: div[class=] .
In CSS, Sublime Text uses slightly different autocomplete behavior by default: it displays completions by default and doesn’t re-populate completions list as you type further, which prevents Emmet from building proper dynamic completion. To overcome this issue, Emmet displays abbreviation preview right after caret as phantom:
If you don’t like inline preview for CSS, you can disable it for CSS only:
- Go to Preferences > Package Settings > Emmet > Settings menu item.
- Set abbreviation_preview option to "markup" , e.g. "abbreviation_preview": "markup" . This will enable previews for markup syntaxes (HTML, XML, JSX etc.) only.
- You can also disable previews completely by setting abbreviation_preview value to false .
Disable abbreviation capturing
To fine tune automatic abbreviation capturing, go to Preferences > Package Settings > Emmet > Settings menu item and update auto_mark option:
- Set value to false to completely disable abbreviation capturing.
- Set value to either "markup" or "stylesheet" to enable capturing for markup (HTML, XML, JSX etc) or stylesheet (CSS, SCSS, LESS etc.) syntaxes only.
For example, if you want abbreviation capturing for HTML and disable it for CSS, set "auto_mark": "markup" . You can also apply the same values for abbreviation_preview option to enable/disable interactive previews completely or for specific syntaxes only.
With abbreviation capturing disabled, you have several options to expand abbreviations manually:
- You can type abbreviation (or put caret behind existing abbreviation) and run Emmet: Expand Abbreviation action from command palette. It is recommended to set keyboard shortcut for this action:
- Another option is to run Emmet: Enter Abbreviation Mode command: the ⋮> mark indicates that you are in explicit abbreviation mode and everything you type will be treated and validated as Emmet abbreviation. You can then hit Tab or Enter key to expand it, Esc to dispose.
It is recommended to add keyboard shortcut for this action as well:
Another new feature of Emmet 2 is inline preview of opening tag. When you move caret inside name of closing tag and its matching open tag is not visible on screen, you’ll see an inline tag preview:
Click on this preview will jump to open tag.
This option is disable by default. To enable it, go to Preferences > Package Settings > Emmet > Settings and set tag_preview option to true .
Adding custom Emmet snippets
To add new Emmet snippets or modify existing ones, tweak core Emmet preferences etc., go to Preferences > Package Settings > Emmet > Settings and modify config key.
You can configure snippets/preferences globally or per syntax. Emmet understands two types of abbreviations: markup (used for markup syntaxes like HTML, Pug, JSX etc.) and stylesheet (for CSS, Sass, Less, etc.). In order to add or modify snippets globally, you should use one of these keys in config section. If you want to set snippets for specific syntax only (for example, only for JSX or HTML), you should use syntax name as a key. Here’s an example config:
All the rest actions like Wrap with Abbreviation, Balance, Select Item etc. are also supported but doesn’t have default key bindings. You should either invoke these actions via Command Palette or create your own keyboard shortcuts (see Default.sublime-commands file for list of available actions).
A convenient way to add key bindings for Emmet commands is to go to Preferences > Package Settings > Emmet > Key Bindings menu and copy required sample bindings from the left side to the right without comments.
In future, Emmet for Sublime Text plugin will provide convenient UI for fine-tuning Emmet options and key bindings.
FAQ about migration from v1
Here are some most frequently asked questions and issues users came up with after updating to Emmet v2:
All my keyboard shortcuts gone/nothing works!
Emmet comes with lots of actions like Wrap with Abbreviation, Balance, Select Item etc. In v1, all these actions had default key bindings. And some of these actions override default ST actions like Go To End of Line ( Ctrl+E ) or actions from default packages. Unfortunately, ST doesn’t provide any means to unbind key bindings coming from packages so it became a real problem for users to properly restore editor behavior.
In Emmet 2, all key bindings are disabled by default so you have to add them manually. But don’t worry, you have to just uncomment them:
- Go to Preferences > Package Settings > Emmet > Key Bindings menu item.
- On the left side you’ll see a sample, commented list of Emmet actions. You just need to copy required actions to the right side and uncomment them.
Tab key doesn’t work anymore
Most likely, you’ve updated Tab key handler for expand_abbreviation_by_tab action from Emmet v1 in your key bindings file: simply remove it, it no longer valid.
I don’t like new behavior with abbreviation capturing, I’d like to expand with Tab as earlier
You can get almost the same abbreviation expansion behavior as in v1:
- Go to Preferences > Package Settings > Emmet > Settings menu item and set auto_mark option to false .
- Add the following into user key bindings (Preferences > Key Bindings menu item) file:
Note that old behavior has lots of downsides: you won‘t be able to expand native ST snippets and use Tab key to insert indentation after word.
In order to work with plugin source code, don’t forget to install py-emmet dependency. After checking out source code, go to repo folder and run
This is the next version of Emmet plugin with greatly improved developer experience and new features. Read below for more details. Plugin is currently in beta stage and may contain bugs.
Emmet is a web-developer’s toolkit for boosting HTML & CSS code writing.
With Emmet, you can type expressions (abbreviations) similar to CSS selectors and convert them into code fragment with a single keystroke. For example, this abbreviation:
…can be expanded into:
Tag preview
Another new feature of Emmet 2 is inline preview of opening tag. When you move caret inside name of closing tag and its matching open tag is not visible on screen, you’ll see an inline tag preview:
Click on this preview will jump to open tag.
This option is disable by default. To enable it, go to Preferences > Package Settings > Emmet > Settings and set tag_preview option to true .
FAQ about migration from v1
Here are some most frequently asked questions and issues users came up with after updating to Emmet v2:
Tab key doesn’t work anymore
Most likely, you’ve updated Tab key handler for expand_abbreviation_by_tab action from Emmet v1 in your key bindings file: simply remove it, it no longer valid.
Adding custom Emmet snippets
To add new Emmet snippets or modify existing ones, tweak core Emmet preferences etc., go to Preferences > Package Settings > Emmet > Settings and modify config key.
You can configure snippets/preferences globally or per syntax. Emmet understands two types of abbreviations: markup (used for markup syntaxes like HTML, Pug, JSX etc.) and stylesheet (for CSS, Sass, Less, etc.). In order to add or modify snippets globally, you should use one of these keys in config section. If you want to set snippets for specific syntax only (for example, only for JSX or HTML), you should use syntax name as a key. Here’s an example config:
Disable abbreviation capturing
To fine tune automatic abbreviation capturing, go to Preferences > Package Settings > Emmet > Settings menu item and update auto_mark option:
- Set value to false to completely disable abbreviation capturing.
- Set value to either "markup" or "stylesheet" to enable capturing for markup (HTML, XML, JSX etc) or stylesheet (CSS, SCSS, LESS etc.) syntaxes only.
For example, if you want abbreviation capturing for HTML and disable it for CSS, set "auto_mark": "markup" . You can also apply the same values for abbreviation_preview option to enable/disable interactive previews completely or for specific syntaxes only.
With abbreviation capturing disabled, you have several options to expand abbreviations manually:
- You can type abbreviation (or put caret behind existing abbreviation) and run Emmet: Expand Abbreviation action from command palette. It is recommended to set keyboard shortcut for this action:
- Another option is to run Emmet: Enter Abbreviation Mode command: the ⋮> mark indicates that you are in explicit abbreviation mode and everything you type will be treated and validated as Emmet abbreviation. You can then hit Tab or Enter key to expand it, Esc to dispose.
It is recommended to add keyboard shortcut for this action as well:
More actions
All the rest actions like Wrap with Abbreviation, Balance, Select Item etc. are also supported but doesn’t have default key bindings. You should either invoke these actions via Command Palette or create your own keyboard shortcuts (see Default.sublime-commands file for list of available actions).
A convenient way to add key bindings for Emmet commands is to go to Preferences > Package Settings > Emmet > Key Bindings menu and copy required sample bindings from the left side to the right without comments.
In future, Emmet for Sublime Text plugin will provide convenient UI for fine-tuning Emmet options and key bindings.
CSS support
In CSS, Sublime Text uses slightly different autocomplete behavior by default: it displays completions by default and doesn’t re-populate completions list as you type further, which prevents Emmet from building proper dynamic completion. To overcome this issue, Emmet displays abbreviation preview right after caret as phantom:
If you don’t like inline preview for CSS, you can disable it for CSS only:
- Go to Preferences > Package Settings > Emmet > Settings menu item.
- Set abbreviation_preview option to "markup" , e.g. "abbreviation_preview": "markup" . This will enable previews for markup syntaxes (HTML, XML, JSX etc.) only.
- You can also disable previews completely by setting abbreviation_preview value to false .
Expanding abbreviation
If you used previous version of Emmet plugin, you already know how to expand abbreviations: type something like ul>li.items*4 and hit Tab or Ctrl-E . While this approach generally works, it has lots of downsides:
- Tab key hijacking: Emmet binds Tab key for expanding abbreviations so user is unable to insert native Sublime Text snippet or put tab right after word since almost every word can be abbreviation for Emmet.
- No preview of expanded abbreviations: writing complex abbreviations becomes trial and error with expand/undo/expand actions.
- Unpredictable result: it’s not possible to determine what happens when you hit Tab key, it will either expand abbreviation, insert native snippet or just output tab character.
In this plugin, abbreviation expander acts as autocomplete provider and automatically captures abbreviation as you type.
When you start typing in Emmet-supported context (HTML, CSS, Slim etc.) Emmet detects if you’re typing something similar to abbreviation and adds underline which indicates captured abbreviation. When captured abbreviation becomes complex (e.g. contains attributes or multiple elements), you’ll see a preview of expanded abbreviation every time caret is inside it. Hit Tab key inside captured abbreviation to expand it, hit Esc to remove mark from abbreviation so you can use Tab for expanding native ST snippets or insert tab character.
If you already have an abbreviation in document and you want to expand it, move caret to the end of abbreviation and invoke autocomplete ( Ctrl+Space by default) to capture abbreviation:
All my keyboard shortcuts gone/nothing works!
Emmet comes with lots of actions like Wrap with Abbreviation, Balance, Select Item etc. In v1, all these actions had default key bindings. And some of these actions override default ST actions like Go To End of Line ( Ctrl+E ) or actions from default packages. Unfortunately, ST doesn’t provide any means to unbind key bindings coming from packages so it became a real problem for users to properly restore editor behavior.
In Emmet 2, all key bindings are disabled by default so you have to add them manually. But don’t worry, you have to just uncomment them:
- Go to Preferences > Package Settings > Emmet > Key Bindings menu item.
- On the left side you’ll see a sample, commented list of Emmet actions. You just need to copy required actions to the right side and uncomment them.
JSX support
Make sure your document syntax is set to JSX, not JavaScript
Writing Emmet abbreviations in JSX is a bit tricky: in most cases you’d expect Tab key to expand native Sublime Text snippets and use Emmet for specific context only. So a default abbreviation capturing for every variable or snippet would annoy you.
To solve this problem, Emmet uses prefixed abbreviations in JSX: it will capture and expand abbreviation only if it’s prefixed with a specific symbol(s). By default, it’s a < character:
Emmet detects camel-cased module notation in JSX: Foo.Bar will be expanded as instead of . Expression attributes are supported as well: div[class=] .
Features
Development
In order to work with plugin source code, don’t forget to install py-emmet dependency. After checking out source code, go to repo folder and run
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Emmet 2 for Sublime Text editor
This is the next version of Emmet plugin with greatly improved developer experience and new features. Read below for more details. Plugin is currently in beta stage and may contain bugs.
Emmet is a web-developer’s toolkit for boosting HTML & CSS code writing.
With Emmet, you can type expressions (abbreviations) similar to CSS selectors and convert them into code fragment with a single keystroke. For example, this abbreviation:
. can be expanded into:
- From Command Palette , run Package Control: Install Package command.
- In opened packages list, find Emmet package and install it
If you’re unable to find Emmet package on last step or installed package doesn’t work as expected, restart Sublime Text and try again
If you used previous version of Emmet plugin, you already know how to expand abbreviations: type something like ul>li.items*4 and hit Tab or Ctrl-E . While this approach generally works, it has lots of downsides:
- Tab key hijacking: Emmet binds Tab key for expanding abbreviations so user is unable to insert native Sublime Text snippet or put tab right after word since almost every word can be abbreviation for Emmet.
- No preview of expanded abbreviations: writing complex abbreviations becomes trial and error with expand/undo/expand actions.
- Unpredictable result: it’s not possible to determine what happens when you hit Tab key, it will either expand abbreviation, insert native snippet or just output tab character.
In this plugin, abbreviation expander acts as autocomplete provider and automatically captures abbreviation as you type.
When you start typing in Emmet-supported context (HTML, CSS, Slim etc.) Emmet detects if you’re typing something similar to abbreviation and adds underline which indicates captured abbreviation. When captured abbreviation becomes complex (e.g. contains attributes or multiple elements), you’ll see a preview of expanded abbreviation every time caret is inside it. Hit Tab key inside captured abbreviation to expand it, hit Esc to remove mark from abbreviation so you can use Tab for expanding native ST snippets or insert tab character.
If you already have an abbreviation in document and you want to expand it, move caret to the end of abbreviation and invoke autocomplete ( Ctrl+Space by default) to capture abbreviation:
Make sure your document syntax is set to JSX, not JavaScript
Writing Emmet abbreviations in JSX is a bit tricky: in most cases you’d expect Tab key to expand native Sublime Text snippets and use Emmet for specific context only. So a default abbreviation capturing for every variable or snippet would annoy you.
To solve this problem, Emmet uses prefixed abbreviations in JSX: it will capture and expand abbreviation only if it’s prefixed with a specific symbol(s). By default, it’s a < character:
Emmet detects camel-cased module notation in JSX: Foo.Bar will be expanded as instead of . Expression attributes are supported as well: div[class=] .
In CSS, Sublime Text uses slightly different autocomplete behavior by default: it displays completions by default and doesn’t re-populate completions list as you type further, which prevents Emmet from building proper dynamic completion. To overcome this issue, Emmet displays abbreviation preview right after caret as phantom:
If you don’t like inline preview for CSS, you can disable it for CSS only:
- Go to Preferences > Package Settings > Emmet > Settings menu item.
- Set abbreviation_preview option to "markup" , e.g. "abbreviation_preview": "markup" . This will enable previews for markup syntaxes (HTML, XML, JSX etc.) only.
- You can also disable previews completely by setting abbreviation_preview value to false .
Disable abbreviation capturing
To fine tune automatic abbreviation capturing, go to Preferences > Package Settings > Emmet > Settings menu item and update auto_mark option:
- Set value to false to completely disable abbreviation capturing.
- Set value to either "markup" or "stylesheet" to enable capturing for markup (HTML, XML, JSX etc) or stylesheet (CSS, SCSS, LESS etc.) syntaxes only.
For example, if you want abbreviation capturing for HTML and disable it for CSS, set "auto_mark": "markup" . You can also apply the same values for abbreviation_preview option to enable/disable interactive previews completely or for specific syntaxes only.
With abbreviation capturing disabled, you have several options to expand abbreviations manually:
- You can type abbreviation (or put caret behind existing abbreviation) and run Emmet: Expand Abbreviation action from command palette. It is recommended to set keyboard shortcut for this action:
- Another option is to run Emmet: Enter Abbreviation Mode command: the ⋮> mark indicates that you are in explicit abbreviation mode and everything you type will be treated and validated as Emmet abbreviation. You can then hit Tab or Enter key to expand it, Esc to dispose.
It is recommended to add keyboard shortcut for this action as well:
Another new feature of Emmet 2 is inline preview of opening tag. When you move caret inside name of closing tag and its matching open tag is not visible on screen, you’ll see an inline tag preview:
Click on this preview will jump to open tag.
This option is disable by default. To enable it, go to Preferences > Package Settings > Emmet > Settings and set tag_preview option to true .
Adding custom Emmet snippets
To add new Emmet snippets or modify existing ones, tweak core Emmet preferences etc., go to Preferences > Package Settings > Emmet > Settings and modify config key.
You can configure snippets/preferences globally or per syntax. Emmet understands two types of abbreviations: markup (used for markup syntaxes like HTML, Pug, JSX etc.) and stylesheet (for CSS, Sass, Less, etc.). In order to add or modify snippets globally, you should use one of these keys in config section. If you want to set snippets for specific syntax only (for example, only for JSX or HTML), you should use syntax name as a key. Here’s an example config:
All the rest actions like Wrap with Abbreviation, Balance, Select Item etc. are also supported but doesn’t have default key bindings. You should either invoke these actions via Command Palette or create your own keyboard shortcuts (see Default.sublime-commands file for list of available actions).
A convenient way to add key bindings for Emmet commands is to go to Preferences > Package Settings > Emmet > Key Bindings menu and copy required sample bindings from the left side to the right without comments.
In future, Emmet for Sublime Text plugin will provide convenient UI for fine-tuning Emmet options and key bindings.
FAQ about migration from v1
Here are some most frequently asked questions and issues users came up with after updating to Emmet v2:
All my keyboard shortcuts gone/nothing works!
Emmet comes with lots of actions like Wrap with Abbreviation, Balance, Select Item etc. In v1, all these actions had default key bindings. And some of these actions override default ST actions like Go To End of Line ( Ctrl+E ) or actions from default packages. Unfortunately, ST doesn’t provide any means to unbind key bindings coming from packages so it became a real problem for users to properly restore editor behavior.
In Emmet 2, all key bindings are disabled by default so you have to add them manually. But don’t worry, you have to just uncomment them:
- Go to Preferences > Package Settings > Emmet > Key Bindings menu item.
- On the left side you’ll see a sample, commented list of Emmet actions. You just need to copy required actions to the right side and uncomment them.
Tab key doesn’t work anymore
Most likely, you’ve updated Tab key handler for expand_abbreviation_by_tab action from Emmet v1 in your key bindings file: simply remove it, it no longer valid.
I don’t like new behavior with abbreviation capturing, I’d like to expand with Tab as earlier
You can get almost the same abbreviation expansion behavior as in v1:
- Go to Preferences > Package Settings > Emmet > Settings menu item and set auto_mark option to false .
- Add the following into user key bindings (Preferences > Key Bindings menu item) file:
Note that old behavior has lots of downsides: you won‘t be able to expand native ST snippets and use Tab key to insert indentation after word.
In order to work with plugin source code, don’t forget to install py-emmet dependency. After checking out source code, go to repo folder and run
This plugin is deprecated and no longer maintained, please use new version.
Emmet for Sublime Text
Official Emmet plugin for Sublime Text.
Warning: this plugin may not work at all in some OSes since it written in JavaScript and uses PyV8 and Google V8 binaries to run. If you experience problems or editor crashes please fill an issue.
- Run “Package Control: Install Package” command, find and install Emmet plugin.
- Restart ST editor (if required)
- Clone or download git repo into your packages folder (in ST, find Browse Packages. menu item to open this folder)
- Restart ST editor (if required)
WARNING: When plugin is installed, it will automatically download required PyV8 binary so you have to wait a bit (see Loading PyV8 binary message on status bar). If you experience issues with automatic PyV8 loader, try to install it manually.
-
– Tab or Ctrl+E
- Interactive “Expand Abbreviation” — Ctrl+Alt+Enter – ⌃D (Mac) / Ctrl+, (PC) – ⌃J / Shift+Ctrl+0 – ⇧⌃T / Ctrl+Alt+J — ⌃W / Shift+Ctrl+G — Ctrl+Alt+→ or Ctrl+Alt+← – ⇧⌘. or ⇧⌘, / Shift+Ctrl+. or Shift+Ctrl+, — ⇧⌥/ / Shift+Ctrl+/ — ⇧⌘' / Shift+Ctrl+` – ⌘' / Shift+Ctrl+; — ⇧⌃I / Ctrl+U — ⇧⌘Y / Shift+Ctrl+Y – ⇧⌘R / Shift+Ctrl+R – ⇧⌃D / Ctrl+'
- Rename Tag – ⇧⌘K / Shift+Ctrl+'
- Increment by 1: Ctrl+↑
- Decrement by 1: Ctrl+↓
- Increment by 0.1: Alt+↑
- Decrement by 0.1: Alt+↓
- Increment by 10: ⌥⌘↑ / Shift+Alt+↑
- Decrement by 10: ⌥⌘↓ / Shift+Alt+↓
You can easily extend Emmet with new actions and filters or customize existing ones. In Emmet.sublime-settings , define extensions_path setting and Emmet will load all .js and .json files in specified folder at startup.
The default value of extensions_path is ~/emmet , which points to emmet folder inside your OS user’s home folder.
Also, you can create sections named as extension files (e.g. snippets , preferences and syntaxProfiles ) inside user’s Emmet.sublime-settings file and write your customizations there. See original settings file for examples.
Overriding keyboard shortcuts
Sublime Text is a great text editor with lots of features and actions. Most of these actions are bound to keyboard shortcuts so it’s nearly impossible to provide convenient plugin shortcuts for third-party plugins.
If you’re unhappy with default keymap, you can disable individual keyboard shortcuts with disabled_keymap_actions preference of Emmet.sublime-settings file.
Use a comma-separated list of action names which default keyboard shortcuts should be disabled. For example, if you want to release Ctrl+E (“Expand Abbreviation”) and Ctrl+U (“Update Image Size”) shortcuts, your must set the following value:
You should refer Default (Your-OS-Name).sublime-keymap file to get action ids (look for args/action key).
To disable all default shortcuts, set value to all :
Not that if you disabled any action like so and you’re create your own keyboard shortcut, you should not use emmet_action_enabled.ACTION_NAME context since this is the key that disables action.
How to expand abbreviations with Tab in other syntaxes
Emmet expands abbreviations in limited syntaxes only: HTML, CSS, LESS, SCSS, Stylus and PostCSS. The reason to restrict Tab handler to a limited syntax list is because it breaks native Sublime Text snippets.
If you want to abbreviation with Tab in other syntaxes (for example, JSX, HAML etc.) you have to tweak your keyboard shorcuts settings: add expand_abbreviation_by_tab command for tab key for required syntax scope selectors. To get current syntax scope selector, press ⇧⌃P (OSX) or Ctrl+Alt+Shift+P , it will be displayed in editor status bar.
Go to Preferences > Key Bindings — User and insert the following JSON snippet with properly configured scope selector instead of SCOPE_SELECTOR token:
Tab key handler
Emmet plugin allows you to expand abbreviations with Tab key, just like regular snippets. On the other hand, due to dynamic nature and extensive syntax, sometimes you may get unexpected results. This section describes how Tab handler works and how you can fine-tune it.
By default, Tab handler works in a limited syntax scopes: HTML, XML, HAML, CSS, SASS/SCSS, LESS, PostCSS and strings in programming languages (like JavaScript, Python, Ruby etc.). It means:
- You have to switch your document to one of the syntaxes listed above to expand abbreviations by Tab key.
- With Ctrl-E shortcut, you can expand abbreviations everywhere, its scope is not limited.
- When you expand abbreviation inside strings of programming languages, the output is generated with special output profile named line that generates output as a single line.
To fine-tune Tab key handler, you can use the following settings in user’s Emmet.sublime-settings file:
- disable_tab_abbreviations_for_scopes — a comma-separated list of syntax scopes where Tab key handler should be disabled. For example, if you want disable handler inside strings of programming languages and HAML syntax, your setting will look like this:
- disabled_single_snippet_for_scopes — a comma-separated list of syntax scopes where Tab handler should be disabled when expanding a single abbreviation. Currently, ST doesn’t provide API for getting list of native snippets. So, for example, if you try to expand a php abbreviation, it will be passed to Emmet which outputs instead of PHP block as defined in native ST snippets. As a workaround, if you’re trying to expand a single abbreviation inside scope defined in disabled_single_snippet_for_scopes setting Emmet will look for its name inside its own snippets catalog first, inside known_html_tags setting second and if it’s not found, it allows ST to handle it and expand native abbreviation, if matched.
- known_html_tags — a space-separated list of all known HTML tags used for lookup as described above.
If you’re unhappy with Emmet tab handler behavior, you can disable it: just add "disable_tab_abbreviations": true into user’s Preferences.sublime-settings file.
Disable automatic vendor prefixes insertion
If your workflow already includes an automated task for CSS vendor prefixing (such as Autoprefixer), you can disable Emmet's automatic vendor prefixes insertion adding this option to your user’s Emmet.sublime-settings file:
I don’t like new behavior with abbreviation capturing, I’d like to expand with Tab as earlier
You can get almost the same abbreviation expansion behavior as in v1:
- Go to Preferences > Package Settings > Emmet > Settings menu item and set auto_mark option to false .
- Add the following into user key bindings (Preferences > Key Bindings menu item) file:
Note that old behavior has lots of downsides: you won‘t be able to expand native ST snippets and use Tab key to insert indentation after word.
Installation
- From Command Palette , run Package Control: Install Package command.
- In opened packages list, find Emmet package and install it
If you’re unable to find Emmet package on last step or installed package doesn’t work as expected, restart Sublime Text and try again
Читайте также: