template #模板文件夾 codemanage.py #插件代碼 Default (XXX).sublime-keymap #快捷鍵配置文件,XXX值平臺 var-map.conf #替換變量配置文件,key=value
codemanage.py代碼以下:
html
#-*- coding: UTF-8 -*- import sublime, sublime_plugin import os import os.path import time import sys reload(sys) sys.setdefaultencoding('utf8') #寫入模板,若是是新模板按照模板名建立一個文件,若是是舊模板則覆蓋寫原文件 class CodeTplAddCommand(sublime_plugin.TextCommand): def run(self,edit): #獲取當前選中內容 selstr = '' sels = self.view.sel() for sel in sels: value = self.view.substr(sel) if value == '': continue selstr = selstr + value + '\n' if selstr == '': sublime.message_dialog("Select content is empty.") return def on_done(name): if name=='': sublime.message_dialog("Template name is empty.") return #寫入文件 path = os.path.join(sublime.packages_path(),"CodeManage","template",name+".ctpl") try: f = open(path, 'w') print selstr selstr.encode("gbk") f.write(selstr) except Exception, e: print e sublime.message_dialog("Write template file fail:"+str(e)) return finally: f.close() def on_change(name): return def on_cancel(): return #輸入模板名 self.view.window().show_input_panel('Plese input the code template name','template',on_done,on_change,on_cancel) #將對應模板插入當前位置 class CodeTplInsertCommand(sublime_plugin.TextCommand): def run(self,edit): filenames = [] rootdir= os.path.join(sublime.packages_path(),"CodeManage","template") for p,d,files in os.walk(rootdir): filenames = files def on_sel_done(selvalue): if selvalue==-1: return filename = filenames[selvalue] content = '' if filename=='': sublime.message_dialog("Template is not exist.") return path = os.path.join(sublime.packages_path(),"CodeManage","template",filename) try: f = open(path, 'r') content = f.read() if content=='': sublime.message_dialog("Template file is empty") return content = ReplaceVar(content) except Exception, e: sublime.message_dialog("Open template file fail:"+str(e)) return finally: f.close() #把內容插入當前位置 sels = self.view.sel() for sel in sels: self.view.insert(edit,sel.begin(),content) #打開選擇列表 self.view.window().show_quick_panel(filenames,on_sel_done) #處理一些模板替換變量 #將模板中{{XXX}}的變量替換成配置文件中的變量({{data}}等信息直接替換) def ReplaceVar(content): varmap = { '{{date}}':time.strftime('%Y-%m-%d',time.localtime(time.time())) } #讀取變量 try: path = os.path.join(sublime.packages_path(),"CodeManage","var-map.conf") f = open(path, 'r') for line in f.readlines(): if line=='': continue value = line.split("=") varmap["{{"+value[0]+"}}"] = value[1] except Exception, e: sublime.message_dialog("Open var-map file fail:"+str(e)) return finally: f.close() for (k,v) in varmap.items(): content = content.replace(k,v) return content懂python應該能夠看出來很是簡單。