Sublime text 3 создание синтаксиса
Syntax definitions make Sublime Text aware of programming and markup languages. Most noticeably, they work together with colors to provide syntax highlighting. Syntax definitions define scopes that divide the text in a buffer into named regions. Several editing features in Sublime Text make extensive use of this fine-grained contextual information.
Essentially, syntax definitions consist of regular expressions used to find text, as well as more or less arbitrary, dot-separated strings called scopes or scope names. For every occurrence of a given regular expression, Sublime Text gives the matching text its corresponding scope name.
For Sublime Text 3 (Build 3084), a new syntax definition format has been added with the .sublime-syntax extension.
It is highly encouraged to be used in favor of the legacy TextMate format described in this document, unless compatibility with older versions or other editors is desired.
Documentation is available at the official documentation
In order to follow this tutorial, you will need to install PackageDev
(opens new window) , a package intended to ease the creation of new syntax definitions for Sublime Text. Follow the installation notes in the "Getting Started" section of the readme.
Sublime Text uses property list
(opens new window) (Plist) files to store syntax definitions. However, because editing XML files is a cumbersome task, we'll use YAML
(opens new window) instead and convert it to Plist format afterwards. This is where the PackageDev package (mentioned above) comes in.
If you experience unexpected errors during this tutorial, chances are PackageDev or YAML is to blame. Don't immediately think your problem is due to a bug in Sublime Text.
By all means, do edit the Plist files by hand if you prefer to work in XML, but always keep in mind their differing needs in regards to escape sequences, many XML tags etc.
Scopes are a key concept in Sublime Text. Essentially, they are named text regions in a buffer. They don't do anything by themselves, but Sublime Text peeks at them when it needs contextual information.
For instance, when you trigger a snippet, Sublime Text checks the scope bound to the snippet and looks at the caret's position in the file. If the caret's current position matches the snippet's scope selector, Sublime Text fires it off. Otherwise, nothing happens.
There's a slight difference between scopes and scope selectors: Scopes are the names defined in a syntax definition, while scope selectors are used in items like snippets and key bindings to target scopes. When creating a new syntax definition, you care about scopes; when you want to constrain a snippet to a certain scope, you use a scope selector.
Scopes can be nested to allow for a high degree of granularity. You can drill down the hierarchy very much like with CSS selectors. For instance, thanks to scope selectors, you could have a key binding activated only within single quoted strings in Python source code, but not inside single quoted strings in any other language.
Sublime Text inherits the idea of scopes from Textmate, a text editor for Mac. Textmate's online manual
(opens new window) contains further information about scope selectors that's useful for Sublime Text users too. In particular, Color Schemes make extensive use of scopes to style every aspect of a language in the desired color.
At their core, syntax definitions are arrays of regular expressions paired with scope names. Sublime Text will try to match these patterns against a buffer's text and attach the corresponding scope name to all occurrences. These pairs of regular expressions and scope names are known as rules.
Rules are applied in order, one line at a time. Rules are applied in the following order:
- The rule that matches at the first position in a line
- The rule that comes first in the array
Each rule consumes the matched text region, which therefore will be excluded from the next rule's matching attempt (save for a few exceptions). In practical terms, this means that you should take care to go from more specific rules to more general ones when you create a new syntax definition. Otherwise, a greedy regular expression might swallow parts you'd like to have styled differently.
Syntax definitions from separate files can be combined, and they can be recursively applied too.
By way of example, let's create a syntax definition for Sublime Text snippets. We'll be styling the actual snippet content, not the whole .sublime-snippet file.
Since syntax definitions are primarily used to enable syntax highlighting, we'll use the phrase to style to mean to break down a source code file into scopes. Keep in mind, however, that colors are a different thing from syntax definitions and that scopes have many more uses besides syntax highlighting.
Here are the elements we want to style in a snippet:
- Variables ( $PARAM1 , $USER_NAME \ . )
- Simple fields ( $0 , $1 \ . )
- Complex fields with placeholders ( $ )
- Nested fields ( $!> )
- Escape sequences ( \$ , \ < , …)
- Illegal sequences ( $ , < , \ , …)
Here are the elements we don't want to style because they are too complex for this example:
Before continuing, make sure you've installed the PackageDev package as explained above.
To create a new syntax definition, follow these steps:
- Go to Tools | Packages | Package Development | New Syntax Definition
- Save the new file in your Packages/User folder as a .YAML-tmLanguage file.
You now should see a file like this:
Let's examine the key elements.
name
The name that Sublime Text will display in the syntax definition drop-down list. Use a short, descriptive name. Typically, you will use the name of the programming language you are creating the syntax definition for.
scopeName
The topmost scope for this syntax definition. It takes the form source. or text. . For programming languages, use source . For markup and everything else, use text .
fileTypes
This is a list of file extensions (without the leading dot). When opening files of these types, Sublime Text will automatically activate this syntax definition for them.
uuid
This is a unique identifier for this syntax definition. Each new syntax definition gets its own uuid. Even though Sublime Text itself ignores it, don't modify this.
patterns
A container for your patterns.
For our example, fill the template with the following information:
YAML is not a very strict format, but can cause headaches when you don't know its conventions. It supports single and double quotes, but you may also omit them as long as the content does not create another YAML literal. If the conversion to Plist fails, take a look at the output panel for more information on the error. We'll explain later how to convert a syntax definition in YAML to Plist. This will also cover the first commented line in the template.
The --- and . are optional.
The patterns array can contain several types of element. We'll look at some of them in the following sections. If you want to learn more about patterns, refer to Textmate's online manual.
Matches take this form:
Sublime Text uses Oniguruma
(opens new window) 's syntax for regular expressions in syntax definitions. Several existing syntax definitions make use of features supported by this regular expression engine that aren't part of perl-style regular expressions, hence the requirement for Oniguruma.
match A regular expression Sublime Text will use to find matches. name The name of the scope that should be applied to any occurrences of match . comment An optional comment about this pattern.
Let's go back to our example. It looks like this:
That is, make sure the patterns array is empty.
Now we can begin to add our rules for Sublime snippets. Let's start with simple fields. These could be matched with a regex like so:
We can then build our pattern like this:
Choosing the Right Scope Name
Naming scopes isn't obvious sometimes. Check the Textmate naming conventions
(opens new window) for guidance on scope names. PackageDev automatically provides completions for scope names according to these conventions. It is important to re-use the basic categories outlined there if you want to achieve the highest compatibility with existing colors.
Color schemes have hardcoded scope names in them. They could not possibly include every scope name you can think of, so they target the standard ones plus some rarer ones on occasion (like for CSS or Markdown). This means that two color schemes using the same syntax definition may render the text differently!
Bear in mind too that you should use the scope name that best suits your needs or preferences. It'd be perfectly fine to assign a scope like constant.numeric to anything other than a number if you have a good reason to do so.
And we can add it to our syntax definition too:
You should use two spaces for indent. This is the recommended indent for YAML and lines up with lists like shown above.
We're now ready to convert our file to .tmLanguage . Syntax definitions use Textmate's .tmLanguage extension for compatibility reasons. As explained above, they are simply Plist XML files.
Follow these steps to perform the conversion:
- Make sure that Automatic is selected in Tools | Build System, or select Convert to . .
- Press Ctrl B . A .tmLanguage file will be generated for you in the same folder as your .YAML-tmLanguage file.
- Sublime Text will reload the changes to the syntax definition.
In case you are wondering why PackageDev knows what you want to convert your file to: It's specified in the first comment line.
You have now created your first syntax definition. Next, open a new file and save it with the extension .ssraw . The buffer's syntax name should switch to "Sublime Snippet (Raw)" automatically, and you should get syntax highlighting if you type $1 or any other simple snippet field.
Let's proceed to creating another rule for environment variables.
Repeat the above steps to update the .tmLanguage file.
You might have noticed, for instance, that the entire text in $PARAM1 is styled the same way. Depending on your needs or your personal preferences, you may want the $ to stand out. That's where captures come in. Using captures, you can break a pattern down into components to target them individually.
Let's rewrite one of our previous patterns to use captures :
Captures introduce complexity to your rule, but they are pretty straightforward. Notice how numbers refer to parenthesized groups left to right. Of course, you can have as many capture groups as you want.
Writing 1 on a new line and pressing tab will autocomplete to '1': thanks to PackageDev.
Arguably, you'd want the other scope to be visually consistent with this one. Go ahead and change it too.
As with ususal regular expressions and substitutions, the capture group '0' applies to the whole match.
Up to now we've been using a simple rule. Although we've seen how to dissect patterns into smaller components, sometimes you'll want to target a larger portion of your source code that is clearly delimited by start and end marks.
Literal strings enclosed by quotation marks or other delimiting constructs are better dealt with by begin-end rules. This is a skeleton for one of these rules:
Well, at least in their simplest version. Let's take a look at one that includes all available options:
Some elements may look familiar, but their combination might be daunting. Let's inspect them individually.
name Just like with simple captures this sets the following scope name to the whole match, including begin and end marks. Effectively, this will create nested scopes for beginCaptures , endCaptures and patterns defined within this rule. Optional. contentName Unlike the name this only applies a scope name to the enclosed text. Optional. begin Regex for the opening mark for this scope. end Regex for the end mark for this scope. beginCaptures Captures for the begin marker. They work like captures for simple matches. Optional. endCaptures Same as beginCaptures but for the end marker. Optional. patterns An array of patterns to match only against the begin-end's content; they aren't matched against the text consumed by begin or end themselves. Optional.
We'll use this rule to style nested complex fields in snippets:
This is the most complex pattern we'll see in this tutorial. The begin and end keys are self-explanatory: they define a region enclosed between $: and > . We need to wrap the begin pattern into quotes because otherwise the trailing : would tell the parser to expect another dictionary key. beginCaptures further divides the begin mark into smaller scopes.
The most interesting part, however, is patterns . Recursion, and the importance of ordering, have finally made their appearance here.
We've seen above that fields can be nested. In order to account for this, we need to style nested fields recursively. That's what the include rule does when we furnish it the $self value: it recursively applies our entire syntax definition to the text captured by our begin-end rule. This portion excludes the text individually consumed by the regexes for begin and end .
Remember, matched text is consumed; thus, it is excluded from the next match attempt and can't be matched again.
To finish off complex fields, we'll style placeholders as strings. Since we've already matched all possible tokens inside a complex field, we can safely tell Sublime Text to give any remaining text ( . ) a literal string scope. Note that this doesn't work if we made the pattern greedy ( .+ ) because this includes possible nested references.
We could've used contentName: string.other.ssraw instead of the last pattern but this way we introduce the importance of ordering and how matches are consumed.
Lastly, let's style escape sequences and illegal sequences, and then we can wrap up.
The only hard thing here is not forgetting that [] enclose arrays in YAML and thus must be wrapped in quotes. Other than that, the rules are pretty straightforward if you're familiar with regular expressions.
However, you must take care to place the second rule after any others matching the $ character, since otherwise it will be consumed and result in every following expression not matching.
Also, even after adding these two additional rules, note that our recursive begin-end rule from above continues to work as expected.
At long last, here's the final syntax definition:
There are more available constructs and code reuse techniques using a "repository", but the above explanations should get you started with the creation of syntax definitions.
If you previously used JSON for syntax definitions you are still able to do this because PackageDev is backwards compatible.
If you want to consider switching to YAML (either from JSON or directly from Plist), it provides a command named PackageDev: Convert to YAML and Rearrange Syntax Definition which will automatically format the resulting YAML in a pleasurable way.
Расширяемость Sublime Text не знает границ. Для тех, кому мало стандартных функций, на Хабре уже рассказывали о том, как создать сниппет, как написать простой плагин, как написать сложный плагин и еще много много чего. Про ручную настройку подсветки синтаксиса толком ничего не смог найти: для кого-то слишком очевидно, кому-то просто не нужна, а кому-то и наверняка же пригодится.
Итак, задача: имея какие-нибудь абстрактные логи доступа в wonder-net:
выделить:
Дату-время — фиолетовым курсивом;
Номер карты — желтым курсивом, если не в черном списке или красным, если иначе;
ip-адрес — темно-зеленым, если не в черном списке или красным, если иначе;
scod=хх — темно-зеленым если 00 или красным, если иначе.
В нашу цветовую схему нужно добавить стили, которыми мы собираемся подсвечивать текст. Насколько я понял, все цветовые схемы аккуратно собраны в файле c:\Program Files\Sublime Text 3\Packages\Color Scheme — Default.sublime-package.
Файл представляет собой zip архив без сжатия. Распаковываем, выбираем любимую схему (по умолчанию Monokai.tmTheme) и копируем ее в…(запускаем Sublime Text: меню Preferences — Browse Packages) папку User.
Открываем свежескопированный Monokai.tmTheme для редактирования. В самом низу перед закрывающимся добавляем блоки стилей. Стиль может содержать три параметра: background, foreground и fontStyle. fontStyle в свою очередь bold, italic и underline.
фиолетовый курсив будет выглядеть так:
жирный желтый(ЖЖ):
2. В той же папке User создаем файл синтаксиса: wonderLog.tmLanguage с содержимым:
На примере видно, что если несколько регулярных выражений претендуют закрасить цвет по-разному, то приоритет будет у того, которое описано выше (первее).
Выбираем пользовательскую цветовую схему: Preferences — Color Scheme — User — Monokai.
Открываем наш чудо-лог (если расширение файла не совпадает с шаблонным, делаем View — Syntax — wonderLog) и наслаждаемся результатом:
Сегодня расскажу о редакторе кода, которым пользуюсь для верстки сайтов уже много лет. Быстрый, удобный и полностью настраиваемый Sublime Text 3.
Мы с нуля настроем его внешний вид, а также применим плагины AutoFileName, BracketHighliter, ColorHighliter, Emmet, GotoCSSDeclaration и Tag, которые существенно помогут нам при верстке сайтов! Ну что ж, от слов к делу!
3. Как определить путь к файлу синтаксиса
Обычно достаточно повторения компьютерного языка через слэш — Python/Python или PHP/PHP , — но иногда это не срабатывает.
2. При помощи PackageResourceViewer
Но что, если нет возможности открыть файл, где необходимый синтаксис успешно применяется? Устанавливаем плагин PackageResourceViewer, PackageResourceViewer: Open Resource → вводим название нашего компьютерного языка/средства программирования — если пользуетесь одним из дефолтных синтаксисов — или плагина — когда нужен синтаксис, внедрённый в плагин. В нашем случае набираем LESS → ищем в выпадающем меню файл с расширением tmLanguage (старый формат синтаксиса в Sublime Text) или sublime-syntax (новый формат) → в рассматриваемом случае это LESS.tmLanguage . $Название плагина/$имя файла синтаксиса без расширения и нужно вставлять напротив параметра syntax в ApplySyntax.
ColorHighliter
Обрати внимание на этот код — это код цвета, но какого именно непонятно.
Разделение рабочего окна
Еще более улучшить восприятие кода и ускорить процесс верстки нам поможет разделение рабочего окна.
Поскольку практически всегда приходится работать с несколькими разными файлами, например index.html style.css и какой-то js файл, то дополнительным удобством будет разделение окна с кодом на секторы. Варинтов несколько. Переходим в View – Layout и смотрим что тут у нас есть.
Соответственно Single – это вид без разделений как сейчас, Columns: 2, 3, 4 это разбивка по вертикали. Например нажав на Columns: 2 наш экран с кодом разделится пополам, и мы можем часть файлов переместить в пустую колонку, например CSS слева HTML и JS справа, что делает работу более наглядной и быстрой.
Так же у нас есть варианты поделить экран по горизонтали это Rows: 2 и Rows: 3, нажав например на Rows: 3 получим три горизонтальных окна и можно перекинуть JS файл в третье окно. И последний вариант это Grid: 4 который делит экран пополам как по горизонтали, так и по вертикали. В результате получаются четыре окна. Обрати внимание, что переключаться между режимами можно и с помощью горячих клавиш Alt+Shift+ соответствующая цифра.
Так что у тебя есть широкий выбор по вкусу. Я чаще всего использую одно разделение по вертикали.
2 Answers 2
A full discussion of how to create a custom syntax is well outside the bounds of something as simple as a Stack Overflow answer. Also I think you're making your problem more complicated than it actually is (although creating a syntax is pretty complicated in general).
In order to walk you through the steps that you would take to create a custom syntax, here's an example.
To start with, create a file with the following contents and save it somewhere as sample.ec , and leave the file open:
You'll notice that the syntax for this file is set to Plain Text (see the status line in the lower right), which is the default syntax for files that are unknown to Sublime.
Now, select Tools > Developer > New Syntax. from the menu. A buffer with the following will appear. Use File > Save to save the file; the location will default to your User package. The name you give it is not important, but make sure that the extension is sublime-syntax . In my example I'm calling my file Sample.sublime-syntax .
Now open the Sublime Console with View > Show Console or press the associated key binding. You'll see that the last line in the console is this:
Leaving the console open, click in the syntax file and perform another save operation again without changing anything. The same line appears in the console again.
- Are there any compile or refresh steps, or does everything automatically reload?
As seen here, every time you modify the syntax definition, the file is recompiled and the results are cached. So there are no compile steps (other than saving) and nothing you need to do in order to refresh anything.
Now lets turn our attention back to the sample file. It's still open, and the syntax still says that it's Plain Text .
Now close the file and re-open it again; a shortcut for this is to use File > Open Recent > Reopen Closed File or it's associated key binding.
Notice that now that the file is re-opened, there are several changes. Firstly, the syntax name in the bottom right side of the window says Sample (or whatever you named your sublime-syntax file above). For another, the contents of the file are now syntax highlighted.
The colors you see are dependent on the color scheme you use, but an example might look like this:
- How do I know that my syntax file, and the scope file it uses, are loaded and applied successfully?
You can see that the syntax file was compiled by the lack of an error message when you save your changes, and you can tell that it's applied by trying to use the syntax.
Here the syntax is being used automatically, but you'll find that if you check View > Syntax in the menu or click the current syntax name in the bottom right of the window, your syntax will appear there. Similarly there is now an entry in the command palette named Set Syntax: Sample (or whatever).
That leads us into your last question. If you go back to your sublime-syntax file, you'll see this at the top:
The first thing to note is that file_extensions includes ec , and our sample file is called sample.ec ; thus this syntax applies to it automatically due to it's name.
Now switch into the sample.ec file, place the cursor somewhere in the buffer and use Tools > Developer > Show Scope Name or press the associated key.
The content of the popup that appears will vary depending on where in the file the cursor is located, but the common point is that the scope that appears always starts with source.example-c .
- In the syntax definition I have to specify a scope (e.g. scope: source.c) but where does that scope file live? Or rather, where do I create my scope file, and how do I name it, so that it loads?
As seen here, there is no such thing as a "scope file"; the sublime-syntax file directly specifies the scope as part of the syntax rules, so it's the only file that you need to create in order to create a syntax. It may look like a filename, but it is not one.
The scopes that are applied in the syntax matching rules in the syntax need to coincide with the scopes in your color scheme in order to be syntax highlighted; that's why you should use the scope naming rules to use the common set of scopes that all syntaxes share unless you're also planning to make a color scheme to go along with your syntax, but unless you use the recommended scopes, your syntax won't work well with other color schemes and your color scheme won't work well for other syntaxes.
From this starting point you can modify the sublime-syntax file here in order to make it highlight files the way you want. That would include changing the base scope at the top, applying an appropriate extension, and then including all of the rules that match your language.
As mentioned above, creating the actual rules to match your file is the most complicated part of creating a syntax unless your file format is very simplistic. It's outside the scope of something that could be conveyed in a Stack Overflow answer, but the official documentation linked above gives you some information on it.
Apart from looking at existing syntax files to see how they're doing what they do, you can also ask more directed questions on the Sublime forum.
Не помню точно, что тогда сделал, но теперь при открытии css или less файлов автоматически ставится синтаксис Pascal. Не знаете, как это убрать? Редактор — Sublime Text 3.
Если нужно просто установить нужный синтаксис, первого способа достаточно, однако плагин добавляет множество возможностей, описанных в документации. Спасибо.
Великий и могучий Emmet
Итак, что же умеет Emmet?
Перейдем в HTML файл и попробуем записать тег div с классом .block, для этого нам теперь достаточно поставить точку, написать "block" и нажать клавишу Tab. Мы получим:
Чтобы сделать более сложную запись, например в тег div с классом .block вставить тег span используем следующую запись:
Жмем клавишу Tab и получаем:
Но и это еще не все, мы можем создавать свои сниппеты, то есть шаблоны/заготовки.
Для этого перейдем Preferences – Package Settings – Emmet – Settings User. Здесь запишем следующее:
Теперь для того чтобы вызвать запись:
нам достаточно написать bl и нажать клавишу Tab
Внешний вид программы
Первым делом, после установки Sublime Text 3, я настраиваю внешний вид программы.
Подсветки синтаксиса
Конечной настройкой внешнего вида будет настройка подсветки синтаксиса. Слово страшное, однако на деле все просто.
Подсветки синтаксиса – это особое окрашивание цветом того или иного елемента в коде. Например, в этой цветовой схеме в HTML файле краcным выделен тег, зеленым — название класса, белым — текст и так далее. Это делает восприятие кода намного понятнее. Обрати внимание на правый нижний угол окна программы, в зависимости от того как кой файл у нас сейчас активен, CSS HTML JS и так далее происходит переключение отображения кода этого конкретного файла.
Зачем же тут что-то делать если все и так отлично работает? Дело в том что в начальном пакете Sublime установлены пакеты подсветки синтаксиса далеко не для всех форматов.
Например, в дальнейшем я планирую работать с файлами SCSS, открыв его я увижу сплошную простыню из набора белых символов. Не очень удобно, правда?
Так вот, в таких случаях я дополнительно устанавливаю нужный пакет.
Открываем наш привычный Commаnd Palette перейдя Tools – Command Palette, либо нажимаем Ctrl+Shift+P набираем install, жмем Install Package Control и ищем дополнение SCSS. Нажимаем на него, после установки мы можем переключить наше отображение на SCSS. Сейчас все выглядит симпатичнее, не так ли?
Настройка внешнего вида редактора важна, так как мы довольно длительное время проводим за написанием кода. Это влияет на нашу усталость, продуктивность, здоровье да и просто на настроение.
Следующее, что мы сделаем это установим ряд плагинов и дополнений. Их существует огромное количество, а я расскажу про основные, которые активно использую сам и которые в разы ускорят весь процесс верстки. Приступим!
1. Без установки дополнительных плагинов
View → Syntax → Open all with current extension as. → LESS → отныне ко всем файлам с расширением less будет автоматически применяться синтаксис LESS .
Дополнительные настройки
Дополнительно повысить восприятие кода и комфорт при работе с ним мне помогут следующие дополнительные настройки. Переходим Preferences – Settings. Открывается такое окно разделенное на две части. В левой части настройки по умолчанию, их изменить нельзя, а вот в правой части ты можешь эти настройки переназначить, каждая следующая должна идти через запятую. Вот какие настройки использую я:
Поясню каждую настройку.
Убирает странные отступы в программе между кодом и боковой панелью, что делает общую картину более компактной.
Выставляет размер шрифта по умолчанию.Также быстро изменить размер шрифта, работая с кодом, можно зажав контрол и покрутив колесо мыши.
Если ты вдруг размер изменил случайно, то сбросить его можно перейдя в Preferences – Font — Reset
Эти линии очень полезны для новичка, потому что визуально соединяют открывающий и закрывающий элемент, что существенно помогает в ориентации в коде.
Лично я отключаю их (false) по двум причинам. Первая — я уже не новичок и без них неплохо справляюсь, вторая причина — это следующая настройка.
Отображает невидимые табуляции и пробелы. То есть это не часть кода, а просто разметка для удобства работы. И вот, если включить и draw_indent_guides и draw_white_space то получатеся кашица которая лично меня напрягает. Что из этого использовать, а что нет — решать тебе.
Размер ширины линии отступа при нажатии Tab. Лично мне нравится 3й размер :)
Например мы работали работали, а потом неожиданно закрыли программу :) Бывает такое? У меня постоянно, так вот эта настройка включает «память» у Sublime и при следующем открытии программы откроются и все последние файлы. И да, память работает и после перезагрузки компа.
Цветовая схема
Далее настраиваю цветовую схему программы и кода, для наглядности открою любой файл, например, с HTML кодом. Для этого два раза кликаю на нужном файле. Теперь перехожу Preferences – Color Scheme, открывается окошко с установленными цветовыми решениями и при выборе той или иной темы внешний вид нашего кода и сама программа будут меняться.
Лично мне не подходит ни один из предустановленных вариантов, поэтому я устанавливаю дополнительную цветовую схему. Огромное их количество можно найти и ознакомиться на сайте с дополнениями к Sublime packagecontrol.io. Я уже знаю какую именно я схему хочу установить, что сейчас и сделаю.
Для того что устанавливать новые цветовые схемы, плагины и прочие дополнения, мне нужно сперва установить установщик этих дополнений. Звучит сложно, но на деле все гораздо проще.
Для этого опять вызываю Command Palette зажимая Ctrl+Shift+P, в поле поиска опять ввожу install пока не увижу пункт Package Control: Install Package (установить пакет дополнения) нажимаю на него. Немного подождав вижу окно со списком всех доступных дополнений к Sublime. Ну, почти всех.
Моя любимая цветовая схема установлена, ты конечно же можешь выбрать себе любую другую.
Общий вид программы мне больше нравится темный, поэтому перехожу Preferences – Theme, и переключаюсь на Adaptive.sublime-theme
Сочетание цветов очень важно для работы с кодом, так как это влияет не только на восприятие, но и на усталость и здоровье твоих глаз. Так что подбери себе цветовую схему так, чтобы тебя ничего в ней не напрягало. И помни про перерывы в работе!
Плагины
Боковая панель
Для отображения панели переходим View – Side Bar – Show Open Files. В этой панели будут отображаться наши проекты, то есть папки и файлы нашей верстки. Для наглядности сейчас добавлю один из них. Все что там нужно сделать — это просто перетащить папку с проектом на нашу панель.
GotoCSSDeclaration
Плагин поможет нам с навигацией в коде. Устанавливаем ровно так же как и предыдущие плагины. Далее назначим горячие клавиши для работы с плагином для этого переходим Preferences – Key Bindings, и пишем следующий код
Где ["ctrl+1"] это и есть нужное сочетание клавиш. Сохраняем Cntr+S.
И вот как это работает. У нас должен быть открыт CSS и HTML файлы. CSS как правило очень большой и найти что-то быстро сложно, но это в прошлом. Например, нам нужно изменить CSS для класса content-mainpage кликаем на него мышкой и нажимаем ctrl+1. Вуаля, мы в нужном месте CSS файла.
Ну и для тех, кто дочитал до этого момента покажу еще один плагин, который установить не так просто, но он точно того стоит.
Зовут его Tag и установить нам придется его вручную. По этой ссылке можно скачать архив с плагином. Далее распаковываем в особую папку программы. Для Windows 10 это C:\Users\[Подставь свое имя пользователя]\AppData\Roaming\Sublime Text 3\Packages. Далее закрываем Sublime и открываем снова и добавляем горячие клавиши открыв Preferences – Key Bindings и дописав следующее:
Где ctrl+` это и есть наше сочетание клавиш.
Итак, для чего же мы проделали весь этот нелегкий путь? Как правило, в процессе написания, кода мы работаем сначала с HTML потом переносим названия классов в CSS и работаем уже там. Так вот этот перенос делать вручную давольно долго. И тут нам на помощь приходит плагин Tag. Сейчас нам достаточно выделить нужный HTML код, нажать наше сочетание клавиш ctrl+`
I'm struggling to find out how to create a new syntax highlighting in Sublime Text 3 using the new .sublime-syntax style definition (most previous answers relate to old ways of doing it).
As of Sublime Text Build 3084, a new syntax definition format has been added, with the .sublime-syntax extension.
But I can't find the most basic piece of information detailing how these tie together!
I'm not trying to create a theme, or tweaking an existing syntax definition. I just want to create syntax highlighting to files with an extension I plan on using for my own purposes.
- In the syntax definition I have to specify a scope (e.g. scope: source.c) but where does that scope file live? Or rather, where do I create my scope file, and how do I name it, so that it loads?
- How do I know that my syntax file, and the scope file it uses, are loaded and applied successfully?
- Are there any compile or refresh steps, or does everything automatically reload?
1 ответ 1
Положим, у нас установлен плагин LESS , но при открытии файлов с расширением less синтаксис определяется как Pascal .
AutoFileName
Дело в том, что в процессе верстки часто приходится подключать различные картинки. Этот плагин в разы облегчает процесс подключения. Установим его. Нажимаем Ctrl+Shift+P далее Install Package Control ищем AutoFileName устанавливаем. Попробуем подключить картинку сейчас. Сразу замечаем появление выпадающего меню со списком локальных файлов. Переходим в нужную папку с картинками и видим тут нужный нам файл, а также его размеры, что тоже пригодится.
1. Через встроенную консоль
Открываем файл, в котором нормально определён синтаксис LESS → Ctrl+' (машинописный обратный апостроф, символ расположен на той же клавише, где кириллическая «ё») → вставляем в открывшуюся консоль следующий код:
На выходе должны получить
2. ApplySyntax
Многофункциональный плагин для работы с автоматическим определением синтаксисов. О прочих его возможностях я рассказал в других ответах.
Устанавливаем плагин через Package Control → Preferences → Package Settings → ApplySyntax → Settings - User → увидите правило "syntaxes": [] . В нём между [квадратными скобками] добавляем следующий код:
Не путайтесь в JSON-синтаксисе, следите за правильной расстановкой кавычек, скобок и запятых.
- extensions — расширение, которому мы настраиваем синтаксис,
- syntax — относительный путь к файлу синтаксиса после Packages и без расширения.
BracketHighliter
Читайте также: