alexandre1985
alexandre1985

Reputation: 1106

Sublime Text 3 set syntax highlight by regex of filename

I want my files that have the filename begining with view_ and ending with _js.php to have the Javascript highlight. Basically if has the regex view_*_js.php.
I already know that I can go to "Preferences > Settings - More > Syntax Specific - User" I can edit an put in the JSON the extensions that I want, but I want it to be by regex of filename.
Does anyone know how I can do it?

Upvotes: 3

Views: 796

Answers (2)

MattDMo
MattDMo

Reputation: 102852

The package you are looking for is ApplySyntax, yet another great plugin by facelessuser. Not only does it apply more sophisticated regex rules to analyze the filename itself, it also parses the file itself (generally just the first few lines) for clues in the cases when multiple kinds of files can have the same extension, such as all the various .rb files in a Ruby on Rails project. It is also completely customizable so you can design your own rules for filenames and file contents.

Upvotes: 3

OdatNurd
OdatNurd

Reputation: 22791

Since Sublime wants to use the file extension to select the syntax by default, I believe something like this would require a plugin to swap the syntax out. There may be something like this on PackageControl although my quick searches didn't pull up anything that seemed to match.

A simple example of a Sublime text 3 plugin that will do this is below which uses the on_load event to swap the syntax as needed. You would save this in your Packages/User folder as e.g apply_syntax.py or something of that nature.

import sublime, sublime_plugin,os,re

class ApplyJSSyntax (sublime_plugin.EventListener):
    def __init__ (self):
        self.file_pattern = re.compile ("^view_.*_js.php$")

    def on_load (self, view):
        if self.file_pattern.match (os.path.basename (view.file_name ())):
            view.set_syntax_file ("Packages/JavaScript/JavaScript.sublime-syntax")

Upvotes: 0

Related Questions