Custom syntax in Sublime Text 3 - sublimetext3

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.
I can find the:
syntax rules
scope naming rules
colour scheme rules
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?
Thanks.

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:
// This is a line comment
if (x == 2)
y = 1
else
z = 1
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.
%YAML 1.2
---
# See http://www.sublimetext.com/docs/3/syntax.html
file_extensions:
- ec
scope: source.example-c
contexts:
main:
# Strings begin and end with quotes, and use backslashes as an escape
# character
- match: '"'
scope: punctuation.definition.string.begin.example-c
push: double_quoted_string
# Comments begin with a '//' and finish at the end of the line
- match: '//'
scope: punctuation.definition.comment.example-c
push: line_comment
# Keywords are if, else for and while.
# Note that blackslashes don't need to be escaped within single quoted
# strings in YAML. When using single quoted strings, only single quotes
# need to be escaped: this is done by using two single quotes next to each
# other.
- match: '\b(if|else|for|while)\b'
scope: keyword.control.example-c
# Numbers
- match: '\b(-)?[0-9.]+\b'
scope: constant.numeric.example-c
double_quoted_string:
- meta_scope: string.quoted.double.example-c
- match: '\\.'
scope: constant.character.escape.example-c
- match: '"'
scope: punctuation.definition.string.end.example-c
pop: true
line_comment:
- meta_scope: comment.line.example-c
- match: $
pop: true
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:
generating syntax summary
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:
// This is a line comment
if (x == 2)
y = 1
else
z = 1
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:
# See http://www.sublimetext.com/docs/3/syntax.html
file_extensions:
- ec
scope: source.example-c
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.

I will shortly answer your questions, someone else can feel free to write a longer guide:
You put your syntax definitions inside a package: Select Preferences > Browse Packages... this should open your file explorer. There you can either create a new folder for a new package or use the User folder, which is the default user package. Inside that create a file YourSyntax.sublime-syntax.
You can open the ST console ctrl+` and it will output that the syntax is loaded and potential errors. You can also press ctrl+shift+p and write Set Syntax: YourSyntax in a buffer to directly see it.
You just need to save the file and it will reload the syntax definition.

Related

Add formatting to certain lines that begin with specific strings in Sublime Text 3?

I am working with a fixed-width file where all lines start with certain strings to denote what they contain.
TXX 12345 1111
TXY 123 1 2222
TXZ 1 2 3 4 5
What I want to happen is that I want to be able to add rulers or any form of formatting to rows that start with the specified text. (For example, I want to be able to set the line to red if the line starts with TXX, but blue if the row starts wtih TXY and so on)
What is the first step towards being able to do this?
Generally speaking, most roads here lead to a plugin of some sort that's doing work for you, though conceivably you could also get some coloring going using a custom syntax definition and alterations to your color scheme.
Which one is the correct one depends on circumstance and what works best for you. The following are some samples, which will work with the output you provided above but which could probably be made more robust (again depending on your use case); think proof of concept stuff.
Rulers
Rulers can only be applied to the file as a whole, not to specific lines. So for something like that you're looking at a plugin which, every time the cursor moves, tries to look at the current line to see what it is and then sets up rulers based on knowing what the line looks like.
A quick example of that is the following; the event listener will only apply to files that have the _fixed_rulers setting applied; simplistically, while you have your file open you can enter view.settings().set("_fixed_rulers", True) in the Sublime console, or if you have a syntax you could put the setting into syntax specific settings, etc.
import sublime
import sublime_plugin
def _get_rulers(line):
if line.startswith('TXX'):
return [4, 10]
if line.startswith('TXY'):
return [4, 8, 10]
if line.startswith('TXZ'):
return [4, 6, 8, 10, 12]
return []
class RulerListener(sublime_plugin.ViewEventListener):
#classmethod
def is_applicable(cls, settings):
return settings.get("_fixed_rulers", False)
def on_selection_modified_async(self):
# Cursor position of the first selection; get the full text of the
# line its on
pt = self.view.sel()[0].b
line = self.view.substr(self.view.line(pt))
self.view.settings().set("rulers", _get_rulers(line))
Since there can be multiple selections but rulers are not line specific, this uses the line the first cursor (based on position, not selection order) and applies rulers to the file based on that.
Regions
Colors can be applied to regions of content via a plugin, in a variety of styles (outlined only, underlined, filled, etc), and the API also allows you to find text regions via regex.
So it's also possible to have regions assigned that give things the color you want. A simple example of that would be this command, which will add/update the regions in the file that's active when you execute the color_line_regions command.
import sublime
import sublime_plugin
class ColorLineRegionsCommand(sublime_plugin.TextCommand):
def run(self, edit):
v = self.view
v.add_regions('_txx', v.find_all('^TXX.*$'), 'region.redish')
v.add_regions('_txy', v.find_all('^TXY.*$'), 'region.bluish')
v.add_regions('_txz', v.find_all('^TXZ.*$'), 'region.purplish')
This example is hard coded and requires you to manually invoke the command; you could also have this trigger in response to a file with a specific name opening, and so on.
As defined here this is a one time thing; if you are actively modifying the content of files, adding or changing lines will not adjust regions unless you run the command again (or, have an event listener listen for on_modified_async and trigger this after a delay, etc).
Syntax Definition
Another potential option is creating a custom syntax definition that recognizes the content of the file and applies the appropriate scopes to color things.
This is a much more complex option (the example below is very bare bones and not nearly production ready, but is a good simple test) in that it requires you to construct the syntax definition, but can yield good results if you put in the work.
What you would actually want to do is create your own custom scopes in your syntax, probably with much more robust rules, and then augment your color scheme to match those. Here we're just hackily using scopes that equate to the proper colors if you happen to be using Mariana as your color scheme.
%YAML 1.2
---
# See http://www.sublimetext.com/docs/syntax.html
file_extensions:
- fixed
scope: text.plain.fixed
name: Fixed Field Data
contexts:
main:
- match: '^TXX.*'
scope: variable.language.python
- match: '^TXY.*'
scope: variable.function.python
- match: '^TXZ.*'
scope: keyword.declaration.class.python
A Mix
The ultimate solution may be a mixture of these; perhaps you want the syntax to provide colors and the rulers plugin to make things easier to view as well (as a bonus, with a custom syntax you can have syntax specific settings, which makes the first plugin easy to deploy when files open).
The above examples just scratch the surface; be sure to check out the API Reference for information on how the plugins are working and for more details. There are also a variety of videos that teach how to create and use plugins on my YouTube channel.

How to create simple Sublime Text 3 custom syntax definition

I'm using Sublime Text build 3126 on a Windows machine, and I'm trying to follow the steps in this documentation for creating a very simple syntax definition file. Here is the example given:
%YAML 1.2
---
name: Z
file_extensions: z
scope: source.c
contexts:
main:
- match: \b(if|else|for|while)\b
scope: keyword.control.c
This doesn't work for me in the same way as this post: no option for this custom definition appears under View > Syntax. The original poster seemed to resolve their issue, but I tried to uninstall and reinstall all of ST3 and related files, but I'm still having the same issue.
There are two things to note here:
The file extension must be .sublime-syntax for ST to treat it as a syntax definition. Using .yaml won't work.
If you save the file in a folder that already contains a syntax definition, a submenu will be created with the name of the folder, and the syntax will be under that. i.e. if you have one syntax definition in Packages/User/, and then save another one, both of them will then appear under the User submenu instead of the main syntax list i.e. View -> Syntax -> User -> Z. Note that you can also use the command palette to find a syntax definition by typing Set Syntax:

How to enable sublime text to take first line as file name while saving?

Earlier the Sublime used to take first line as file name by default but now it's "untitled". Is there a way to enable it or is there a plugin for that?
Thanks
The first line is only used as the file name for unsaved files when the syntax is set to Plain Text. As soon as you change the syntax highlighting and type something, it will change the tab name to "untitled".
The implementation for this is in the Default package, set_unsaved_view_name.py file. To get it to work for all syntaxes:
Install PackageResourceViewer through Package Control if it is not already installed
Open Command Palette
Type PRV: and select PackageResourceViewer: Open Resource
Select Default
Select set_unsaved_view_name.py
Find if syntax != 'Packages/Text/Plain text.tmLanguage':
Select from there to the end of the if statement (the first return statement) (Python is indentation based) inclusive return to be commented out.
Go to the Edit menu -> Comment -> Toggle Comment
Save the file
Ensure that, in your preferences (user, syntax specific etc.), set_unsaved_view_name is not set to false
Note: these instructions are valid as at ST build 3131, and the implementation could change in future builds.

Sublime Text 3 specific file type settings only has JSON file settings. How to create new?

I'm trying to create a syntax specific settings for file types in ST3. As per the documentation I am supposed to find what I need in
Sublime Text>Preferences>Settings - More>Syntax Specific - User
However, when I click that I only get JSON.sublime-settings file. What if I want some other settings file?
The settings file that opens when you select Prefereces > Settings - Syntax Specific is sensitive to the type of file that you're currently editing. So, if you happen to be in a JSON file when you invoke the menu command, you get the file for settings specific to JSON.
In order to get at the setting specific to a different syntax, open a file of that type first, or create an empty buffer and set the syntax to the desired language via View > Syntax from the menu, the command palette, or the menu that pops up when you click the file type in the right side of the status bar (where it will say Plain Text).
The file that you actually want to save is SyntaxName.sublime-settings in your User package, e.g. Python.sublime-settings for Python, etc. However to forestall any problems with the filename (like incorrect case or spelling) it's generally better to do it as above instead, particularly since the name of the syntax can sometimes be non-obvious.

Change SublimeREPL shell colour

I use SublimeText3 and try to change the colour for SublimeREPL Shell because its all white. Is that possible? Or is it possible to use colours from system prompt like PS1='' ?. I am running on ubuntu. I haven't found a soloution.
I assume you're trying to color the prompt in the SublimeREPL shell - if you want syntax highlighting of the commands you type, just change the syntax to Shell Script (Bash). To do this permanently, open your Packages folder (Preferences -> Browse Packages...), browse to SublimeREPL/config/Shell, and open Main.sublime-menu as a JSON file. Line 26 contains the "syntax" setting; just change the value to "Packages/ShellScript/Shell-Unix-Generic.tmLanguage", save the file, and the next time you start it the syntax will be applied.
However, if you're just trying to color the prompt, you'll have much more work to do. First, you'll have to create a custom .tmLanguage syntax definition file creating scopes for the various parts of the prompt you want to highlight, then you'll need to alter your color scheme's .tmTheme file to actually style the scopes. (If you're using the ST3 dev builds and have Build 3084 or newer, you can also use the new YAML-based .sublime-syntax format instead of the XML-based .tmLanguage one.)
If you're not using a dev build, the best way to write syntax definitions is to use the wonderful PackageDev package. I maintain an alternate - and better :) - syntax definition for Python and I much prefer using PackageDev's .YAML-tmLanguage format, which as you can tell is also based on YAML, but was around long before the new "official" .sublime-syntax format, and of course they're incompatible. However, it is quite easy to convert from YAML-tmL to tmL to sub-syn and back again, so it's no big deal.
However, as I was saying, the contents of your syntax definition will vary depending on the exact structure of your prompt, and what you want to do with it. For the following examples, I'm assuming you have the default Ubuntu user#hostname:/present/working/directory$ prompt. To create a new syntax definition, after installing PackageDev, select Tools -> Packages -> Package Development -> New Syntax Definition and you'll get the following:
# [PackageDev] target_format: plist, ext: tmLanguage
---
name: Syntax Name
scopeName: source.syntax_name
fileTypes: []
uuid: 7e1549b3-fb0b-44fc-a153-78a7fc2157c2
patterns:
-
...
The first line is required, don't mess with it. You can make name whatever you want. scopeName is obviously the identifier for the base scope, perhaps something like source.shell.prompt. fileTypes can be left blank, and the uuid left alone as well.
If you want to get a feel for how these files are supposed to work, feel free to check out PythonImproved.YAML-tmLanguage on Github, and also make use of the Sublime Text Unofficial Documentation page on the subject as well as the reference. There's also some info in PackageDev's README.
I'll let you develop the rest of the regexes, but here's one for matching the username to get you started:
# [PackageDev] target_format: plist, ext: tmLanguage
---
name: Shell Prompt
scopeName: source.shell.prompt
fileTypes: []
uuid: 7e1549b3-fb0b-44fc-a153-78a7fc2157c2
patterns:
- name: meta.username.prompt
match: ^([A-Za-z_][A-Za-z0-9_-]{0,31})(?=#)
...
You can see it working here.
Once your .YAML-tmLanguage is complete, save the file, open the command palette, and select PackageDev: Convert (YAML, JSON, PList) to.... This will build the .tmLanguage file and put it in the same directory as the .YAML-tmLanguage file. If it's not already under the Packages directory tree, copy it to your Packages/User directory, then modify the Main.sublime-menu file as described in the first paragraph. Finally, open your color scheme's .tmTheme file and edit it to add the scopes defined in your new syntax. Save it, restart Sublime for good measure, and you should be all set!

Resources