如何在Sublime中快速切换主题
Sublime中切换颜色主题有两种办法, 一个是在菜单里面选, 一个是编辑Preferences: Settings - User文件的color_scheme属性. 两个都不怎么方便, 用的较多的主题至少有两个一个是夜间的, 一个是白天的, 一个暗的一个亮的. 如果是Emacs就比较好办了, 一般就是写两个ELISP函数, 用的时候M-x这两个函数即可, 下面是我所用的.
(defun day () (interactive) (load-theme 'leuven) (font-set) ) (defun dark () (interactive) (load-theme 'wombat) (font-set) )
但是Sublime虽然有内置的Python解释器, 但是并不像Emacs那么可以直接加载Python文件, 而必须通过插件, 在Sublime中又叫做Package的方式来给Sublime添加扩展功能.
这里我们没有创建新的的Package, 而是在一个开源的Package的基础上添加了我需要的功能. 先安装ColorScheme Selector这个Package.
安装之后用zip解压器查看里面的的ColorSchemeSelector.py文件和Default.sublime-commands. 这是我们要修改的文件.
先简单介绍一下这两个文件, 例如下面的代码是枚举Sublime中已经安装的主题
if int(sublime.version()) > 3000: color_schemes = sublime.find_resources("*.tmTheme") else: color_schemes = [ "All Hallow's Eve", "Amy", "Blackboard", "Cobalt", "Dawn", "Eiffel", "Espresso Libre", "IDLE", "LAZY", "Mac Classic", "MagicWB (Amiga)", "Monokai Bright", "Monokai", "Pastels on Dark", "Slush & Poppies", "Solarized (Dark)", "Solarized (Light)", "SpaceCadet", "Sunburst", "Twilight", "Zenburnesque", "iPlastic" ]
下面是设置主题, 从上面的数组中选择一个
self.set_color_scheme(color_schemes[index])
而Default.sublime-commands定义了添加到command palette中的命令
[ { "caption": "ColorSchemeSelector: Select Color Scheme", "command": "select_color_scheme" }, { "caption": "ColorSchemeSelector: Random Color Scheme", "command": "select_color_scheme", "args": {"random": true} }, { "caption": "ColorSchemeSelector: Previous Color Scheme", "command": "select_color_scheme", "args": {"direction": "previous"} }, { "caption": "ColorSchemeSelector: Next Color Scheme", "command": "select_color_scheme", "args": {"direction": "next"} } ]
下面是我们要添加的命令
{ "caption": "day", "command": "select_color_scheme", "args": {"direction": "day"} }, { "caption": "dark", "command": "select_color_scheme", "args": {"direction": "dark"} }
这相当于给插件传参数direction, 在代码中接受并处理参数的代码如下
def move_color_scheme(self, color_schemes, direction): def index_containing_substring(the_list, substring): for i, s in enumerate(the_list): if substring in s: return i return -1 current_index = self.current_scheme_index(color_schemes) if direction == 'previous': index = current_index - 1 elif direction == 'next': index = current_index + 1 if current_index < len(color_schemes) else 0 elif direction == 'day': index = index_containing_substring(color_schemes, 'Mac Classic') elif direction == 'dark': index = index_containing_substring(color_schemes, 'Pastels on Dark') else: raise ValueError self.set_color_scheme(color_schemes[index])
把修改后的两个文件重新打包回去, 重启Sublime, 然后就可以在command palette中调用这两个命令了.