public
Last active — forked from JeanMertz/syntax_highlighting.py

Syntax highlight switcher for Sublime Text 2

  • Download Gist
syntax_highlighting.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
import sublime, sublime_plugin
import os, string, re
 
class DetectFileTypeCommand(sublime_plugin.EventListener):
""" Attempts to choose the correct syntax when more than one could apply. """
 
 
def __init__(self):
super(DetectFileTypeCommand, self).__init__()
self.path = None
self.name = None
self.ext = None
self.first_line = None
self.view = None
 
 
def on_load(self, view):
self.check_syntax(view)
 
# As of build 2150, this callback is no longer necessary as the on_post_save works as
# expected (meaning the syntax set in that callback does not get overwritten by something
# after the callback finishes).
# def on_activated(self, view):
# self.check_syntax(view)
 
def on_post_save(self, view):
self.check_syntax(view)
 
def check_syntax(self, view):
self.view = view
self.file_name = view.file_name()
if not self.file_name: # buffer has never been saved
return
 
self.reset_cache_variables()
 
if self.is_xml():
return
 
if self.is_rspec():
return
 
if self.is_cucumber():
return
 
if self.is_rails():
return
 
if self.is_ruby():
return
 
if self.is_php():
return
 
if self.is_apache():
return
 
 
def is_rspec(self):
if self.name.find('_spec') > -1:
self.set_syntax('RSpec')
return True
 
return False
 
 
def is_cucumber(self):
if re.search('steps$', self.name):
self.set_syntax('Cucumber Steps', 'Cucumber')
return True
 
return False
 
 
def is_rails(self):
if self.name.find('gemfile') == 0:
self.set_syntax('Ruby on Rails', 'Rails')
return True
 
if self.ext == '.haml':
self.set_syntax('Ruby Haml', 'Rails')
return True
 
# start at the deepest level and look for <current_dir>/config/routes.rb, working
# backward until it is found or we run out of directories.
 
in_rails_dir = False
 
path = self.path
while path != '':
if os.path.exists(path + '/config/routes.rb'):
in_rails_dir = True
break
else:
dirs = path.split('/')
dirs.pop()
path = '/'.join(dirs)
 
if self.ext in ['.rb', '.rake'] and in_rails_dir:
self.set_syntax('Ruby on Rails', 'Rails')
return True
 
return False
 
def is_ruby(self):
if self.ext == '.rb':
self.set_syntax('Ruby')
return True
self.set_first_line()
 
if self.first_line.find('#!') == 0 and self.first_line.find('ruby') > -1:
self.set_syntax('Ruby')
return True
 
return False
 
 
def is_xml(self):
if self.ext == '.xml':
self.set_syntax('XML')
return True
 
self.set_first_line()
 
if self.first_line.find('<?xml') == 0:
self.set_syntax('XML')
return True
 
return False
 
def is_apache(self):
if self.name in ['.htaccess', '.htpasswd', '.htgroups', 'httpd.conf']:
self.set_syntax('Apache')
return True
 
return False
 
 
def is_php(self):
if self.ext == '.tpl':
self.set_syntax('Smarty', 'PHP')
return True
return False
 
 
def reset_cache_variables(self):
self.path = os.path.dirname(self.file_name)
self.name = os.path.basename(self.file_name).lower()
self.name, self.ext = os.path.splitext(self.name)
 
self.first_line = None
 
 
def set_first_line(self):
with open(self.file_name, 'r') as f:
self.first_line = f.readline()
 
 
def set_syntax(self, syntax, path = None):
if path is None:
path = syntax
new_syntax = 'Packages/' + path + '/' + syntax + '.tmLanguage'
current_syntax = self.view.settings().get('syntax')
 
if current_syntax != new_syntax:
self.view.settings().set('syntax', new_syntax)
print "Switched syntax to: " + syntax

This started as a simple fork (source indicated above), but I wanted to distinguish between Ruby files in a Rails project and regular Ruby files, so it quickly grew into more than just a switcher for Rails. Some of this might be overkill, but it's okay with me (for now). I have very little experience in Python (this is my first real script), so constructive criticism will be appreciated.

I forgot to mention that the on_activated hook is there because (at the time of writing), ST2 assigns the syntax after the on_post_save callback is executed, so even though the syntax can be determined on a newly created file, ST2 overwrites it. The on_activated hook allows you to click off then back onto a newly created file to get the proper syntax. This is with build 2139, but I was told on the forum that it should work the way one expects it to in build 2150, so the on_activated hook may need to come out.

I have confirmed that the on_post_save works as expected in build 2150, so the on_activated hook is no longer necessary. As such, I made appropriate comments in the gist.

Imo, this should be distributed as a package installable with Package Control.

+1 for Package Controll

@maxim/@omarramos

While I appreciate the fact that you find this useful, it was intended to be a personal solution. It is, by no means, thorough. As far as I know, ST2 does a pretty good job of properly identifying file types and choosing the correct syntax. The reason I put it here is so fellow ST2 users could use it to create their own personal syntax selecting solution.

I'll give some thought to making it a package and putting it on GitHub for all to use and improve.

How can I install it?

@odedharth

Save it to a *.py file in your Packages/User directory. On a Mac, this would be ~/Library/Application Support/Sublime Text 2/Packages/User. I don't know where it is on Windows or Linux.

@maxim/@omarramos

Okay, you guys win, sort of :)

I took what I did in DetectFileType and created DetectSyntax (1), which does the same things, but based on rules that you create. The trickiest part was the idea of a Ruby file being in a Rails project, but I solved that with the notion of you (the user) supplying your own function that provides the criteria for the rule. Check it out and let me know what you think. I'm especially open to code and documentation improvements. I'm also interested in hearing if it works on Windows or Linux. I use a Mac and have no idea what it will do on the others. It should work okay, but I'd like to know for certain.

I've submitted a pull request to get it included in Package Control, so hopefully it will show up there soon.

(1) https://github.com/phillipkoebbe/DetectSyntax

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.