How To Make a Custom Syntax Highlighting for Sublime Text
Sublime Text editor has built-in syntax highlighting support for too many languages. In case none of the supported highlightings covers your needs you can create your own. The idea of writing custom syntax definitions first came to light (for me) while looking at the log files generated by one of our games (By the way, I am working at PeakGames and we are building awesome mobile games). If the log file contains a lot of information it may be difficult to see the most important parts. Using tools like grep does not really help if you want to see the whole context.
Here is a step by step guide to write your custom syntax highlighting for Sublime Text editor:
1. Install ‘Package Control’
Package Control is a package manager for Sublime Text that makes it simple to find, install and keep packages up-to-date.
2. Install ‘PackageDev’ Package
PackageDev is a Sublime Text package that helps create and edit syntax definitions, snippets, completions files, build systems and other Sublime Text extension files.
3. Create A New Syntax Definition
After installing PackageDev, create a new syntax definition file through Tools | Packages | Package Development as seen in the screenshot below.
4. Define Your Syntax
Defining a syntax is simply writing regular expressions to find text in the document. Here is an official documentation about writing syntax definitions for Sublime Text. In this step you need to write regular expressions to match the text in your documents. I have used this online tool to test the regular expressions.
Below is a syntax definition file for our logs. It is good for a starting point because it is simple.
Line Number | Keyword | Description |
---|---|---|
3 | name | Name of your syntax definition. You can select syntax of the document in Sublime Text by View->Syntax as seen in the screenshot below. |
4 | scopeName | This will be used while defining colors in the color theme definition files. |
5 | fileTypes | Sublime text automatically chooses your syntax definition if the file type matches. You can choose the syntax definition explicitly by View->Sytax menu. |
5. Define Your Colors
In this step we are going to set colors and text styles (bold, italic vs). Our syntax definition will match the text with the regular expressions and the color theme will change the color and style of the displayed text. Open your favorite color theme. Here is the path to the theme file for Monokai in my computer.
Below is a sample that defines color and text style for text.command pattern (this was defined in the syntax definition on line 9 in the gist above).
That’s it. Now the log files are looking much more meaningful when opened in the Sublime Text editor.