Skip to content

Instantly share code, notes, and snippets.

@phillipkoebbe
Forked from JeanMertz/syntax_highlighting.py
Created December 19, 2011 16:07
Show Gist options
  • Save phillipkoebbe/1497794 to your computer and use it in GitHub Desktop.
Save phillipkoebbe/1497794 to your computer and use it in GitHub Desktop.
Syntax highlight switcher for Sublime Text 2
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
@phillipkoebbe
Copy link
Author

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.

@phillipkoebbe
Copy link
Author

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.

@phillipkoebbe
Copy link
Author

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.

@maxim
Copy link

maxim commented Jan 1, 2012

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

@omarramos
Copy link

+1 for Package Controll

@phillipkoebbe
Copy link
Author

@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.

@odedharth
Copy link

How can I install it?

@phillipkoebbe
Copy link
Author

@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.

@phillipkoebbe
Copy link
Author

@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

@hinxx
Copy link

hinxx commented May 25, 2019

Will this work on ST3?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment