标签:
import sublime, sublime_plugin, datetime
import webbrowser
import re
import urllib.request,os
import threading
import json
import sublime_api
import sys
# D:\Program Files\Sublime Text 3\Data\Packages\User\testone_config.sublime-settings
# my_path=‘D:\\Program Files\\Sublime Text 3\\Data\\Packages\\User\\Packages\\‘
# if not my_path in sys.path:
# sys.path.append(my_path)
# import testone_config
# 通用的参数设置
v_test_url=‘http://mynotes.com/test‘
v_test_dir=‘E:/www/mynotes/test‘
v_test_web=‘E:\\www\\‘
v_test_diru=v_test_dir.replace(‘/‘,‘\\‘)
v_svn_dir=‘E:\文件导出\contraSaver‘
v_plug_dir=‘D:/Program Files/Sublime Text 3/Data/Packages/SubPhp‘
v_add_file_sublime=v_test_diru+‘\\case\\999999981_runtp\\Cruntp.txt‘
# 还要设置一个主题的目录,D:\Program Files\Sublime Text 3\Data\Packages\Theme - Soda
# 公司电脑: USER-20160705YG 家里电脑: FBLCOWTLBYZQU6Q
def isComputerHome():
if getComputerName() == ‘FBLCOWTLBYZQU6Q‘:
isHome=True
else:
isHome=False
return isHome
# 获取当前电脑名称
def getComputerName(ComputerName=[]):
if ComputerName !=[]:
return ComputerName[0]
else:
import socket
Name = socket.getfqdn(socket.gethostname( ))
ComputerName.append(Name)
return Name
# 设置和获取项目的类型,和目录
def get_xm_type(func):
# 项目类型表
mx_type_ar=[[‘tp‘,‘ecshop‘,‘shopnc‘],[
[‘test1‘,‘test2‘,‘test3‘,‘test4‘,‘test5‘,‘test6‘,‘heboxiu‘,‘mynotes‘,‘syntp‘],
[‘ecshop‘,‘liudao‘,‘myWeb‘,‘xipao‘,‘jindou‘],
[‘hunuomall‘,‘shopmc‘,‘zhourou‘]]]
# 查找项目名称
xm=re.compile(r‘[^/]*//([^/]+)/[^ ]*‘) .sub(r‘\1‘,func)
xm=re.compile(r‘[wW]{3}\.(.+)‘) .sub(r‘\1‘,xm)
xm=re.compile(r‘([^\.]+)\..*‘) .sub(r‘\1‘,xm)
xm_ty=‘‘
for i,xm_t in enumerate(mx_type_ar[1]):
if xm in xm_t:xm_ty=mx_type_ar[0][i]
if xm_ty != ‘‘:break
return xm,xm_ty
# config_obj= sublime.load_settings("testone_config.sublime-settings")
class ttttCommand(sublime_plugin.TextCommand):
def run(self,edit,text=‘‘):
print(43564)
class yyyCommand(sublime_plugin.TextCommand):
def run(self,edit,text=‘‘):
mark=self.view.sel()[0]
line_text=self.view.substr( self.view.line(mark.a) )
row_to=re.findall(r‘\s+(\d+):.*‘,line_text)
if row_to :
row_to=row_to[0]
row_s=self.view.rowcol(mark.a)[0]-1
i=0
file=‘‘
while row_s >= 0 and i<100:
line = self.view.substr( self.view.line(self.view.text_point(row_s,0)) )
row_s-=1
i+=1
ba=re.findall(‘^\s+(\w:[\w\\\.]+):\s*‘,line)
if ba:
file=ba[0]
break
if not file == ‘‘:
sublime.active_window().open_file(file+":"+row_to, sublime.ENCODED_POSITION )
else:
return;
def get_word(view,mark,type_r,one=True):
func=‘‘
mark_line=view.line(mark.a)
func_a = view.substr( sublime.Region(mark_line.a,mark.a) )
func_b = view.substr( sublime.Region(mark.a,mark_line.b) )
if type_r == ‘r‘: # 获取单词的正则 函数 方法名
back_a=re.findall(r‘([\w_]+)$‘,func_a)
back_b=re.findall(r‘(^[\w_]+)[\(\"\‘>\.\s=:]?‘,func_b)
elif type_r == ‘c‘: # 获取单词的正则 css名
back_a=re.findall(r‘([\w_-]+)$‘,func_a)
back_b=re.findall(r‘(^[\w_-]+)[\(\"\‘>\.\s=:]?‘,func_b)
elif type_r == ‘w‘: # 获取单词的正则 文件名
back_a=re.findall(r‘[\)\"\‘>\s=:]?([\w_/\\]+)$‘,func_a)
back_b=re.findall(r‘(^[\w_\./\\]+)[\(\"\‘>\s=:]?‘,func_b)
else:
back_b=re.findall(r‘(^[ma\w_]+)[\"\‘\(]‘,func_b)
back_a=re.findall(r‘[\"\‘>\.\s]([\w_]+)$‘,func_a)
if one:
if back_a and back_b: func = back_a[0] + back_b[0]
else:
if back_a : func= back_a[0]
if back_b : func+= back_b[0]
return func
def reg_function(func,type_r):
if func == ‘‘: return ‘‘
for t in type_r:
if t==‘n‘:
strinfo=re.compile(r‘\n‘,re.M)
func=strinfo.sub(r‘‘,func)
if t==‘ss‘:
strinfo=re.compile(r‘^[ \s]*‘,re.M)
func=strinfo.sub(r‘‘,func)
if t==‘l‘: # 空行
strinfo=re.compile(r‘\n[ \s]*\n‘)
func=strinfo.sub(r‘\n‘,func)
return func
# 把当前文件添加到有 Cruntp.txt 的sublime text 里
class addfilecruntpCommand(sublime_plugin.TextCommand):
def run(self,edit,text=‘‘):
window = sublime.active_window()
mark=self.view.sel()[0]
row=self.view.rowcol(mark.a)[0]
url=self.view.file_name()
fal=False
for su in sublime.windows():
for view in su.views():
func=view.file_name()
if func == v_add_file_sublime:
fal=True
break
if fal:break
if fal:
su.open_file(url+":"+str(row), sublime.ENCODED_POSITION )
# su.open_file( url )
# ctrl+alt+r 根据文档里的内容打开文件并跳转到指定的行
class open_file_rowCommand(sublime_plugin.TextCommand):
def run(self,edit,text=‘‘):
mark=self.view.sel()[0]
line_text=self.view.substr( self.view.line(mark.a) )
row_to=re.findall(r‘\s+(\d+):.*‘,line_text)
if row_to :
row_to=row_to[0]
row_s=self.view.rowcol(mark.a)[0]-1
i=0
file=‘‘
while row_s >= 0 and i<100:
line = self.view.substr( self.view.line(self.view.text_point(row_s,0)) )
row_s-=1
i+=1
ba=re.findall(‘^\s*(\w:[\w\\\.]+):\s*‘,line)
if ba:
file=ba[0]
break
if not file == ‘‘:
sublime.active_window().open_file(file+":"+row_to, sublime.ENCODED_POSITION )
else:
return;
class SaveOnModifiedListener(sublime_plugin.EventListener):
def on_modified(self, view):
if not view.file_name():
size=view.size()
if size < 30000:
config_obj= sublime.load_settings("testone_config.sublime-settings")
config_ar_panel=config_obj.get("config_ar_panel")
if not config_ar_panel[1] == 1:
config_ar_panel[0][config_ar_panel[1]]=view.substr( sublime.Region(0,size) )
config_obj.set("config_ar_panel", config_ar_panel)
# sublime.save_settings("testone_config.sublime-settings")
# def on_post_save(self, view):
# sublime.save_settings("testone_config.sublime-settings")
# 标签整理
class tihuan_biaoqianCommand(sublime_plugin.TextCommand):
def run(self, edit):
mark = self.view.sel()[0]
window = sublime.active_window()
func = self.view.substr( mark )
strinfo3=re.compile(r‘(^[^~]*<[^/]*/[^>]*>[^<]*)(<[^/]*/[^>]*>[^<]*$)‘,re.M)
strinfo=re.compile(r‘(<[dhpeslmtia][^/>]*>)+‘)
func=strinfo.sub(r‘\n\1‘,func)
back_b=re.findall(r‘\n[^\n][^\n]*‘,func)
for st in back_b :
st_2=strinfo3.sub(r‘\1\n\2‘,st)
func = func.replace(st,st_2)
self.view.replace(edit, mark, func)
window.run_command( ‘code_formatter‘)
# ctrl+shift+r 产生序列号
class xulie_haoCommand(sublime_plugin.TextCommand):
def run(self,edit,tr=‘all‘):
i=1
l=len(str(len(self.view.sel())))
for mark in self.view.sel():
p=‘‘
j=0
si=str(i)
# num=l-len(si)
# while num > j:
# p+=‘0‘
# j+=1
self.view.insert(edit,mark.a,p+si)
i+=1
# ctrl+q 格式if else
class kong_hangCommand(sublime_plugin.TextCommand):
def run(self,edit,tr=‘all‘):
mark = self.view.sel()[0]
func = self.view.substr( mark )
if func == ‘‘:
mark=sublime.Region(0, self.view.size())
func = self.view.substr( mark )
if tr==‘l‘: func=reg_function(func,[‘l‘])
else:
strinfo1=re.compile(r‘(if\s?\([^\{;]*\))[\s\r\n]+\{‘,re.M)
strinfo2=re.compile(r‘\}[\s\r\n]*(else\s?if)[\s\r\n]*\(‘,re.M)
strinfo4=re.compile(r‘\}[\s\r\n]*(else)[\s\r\n]*\{‘,re.M)
strinfo6=re.compile(r‘(foreach\s?\([^\{;]*\))[\s\r\n]+\{‘,re.M)
func=strinfo1.sub(r‘\1{‘,func)
func=strinfo2.sub(r‘}\1(‘,func)
func=strinfo4.sub(r‘}\1{‘,func)
func=reg_function(func,[‘l‘])
func=strinfo6.sub(r‘\1{‘,func)
self.view.replace(edit, mark, func)
# alt+w 更改缩进 4空格改成2个空格
class shift_tabCommand(sublime_plugin.TextCommand):
def run(self,edit,tr=2):
window = sublime.active_window()
## 四个变两个
# window.run_command( ‘set_setting‘,{"setting": "tab_size", "value": 4} ) #
# window.run_command( ‘expand_tabs‘,{"set_translate_tabs": True} ) # 转换为空格缩进
# window.run_command( ‘unexpand_tabs‘,{"set_translate_tabs": True} ) # 转换为标签缩进
# window.run_command( ‘set_setting‘,{"setting": "tab_size", "value": 2} ) #
# window.run_command( ‘expand_tabs‘,{"set_translate_tabs": True} ) # 转换为空格缩进
ar=tr.split(‘-‘)
window.run_command( ‘set_setting‘,{"setting": "tab_size", "value": int(ar[0])} ) #
window.run_command( ‘expand_tabs‘,{"set_translate_tabs": True} ) # 转换为空格缩进
window.run_command( ‘unexpand_tabs‘,{"set_translate_tabs": True} ) # 转换为标签缩进
window.run_command( ‘set_setting‘,{"setting": "tab_size", "value": int(ar[1])} ) #
window.run_command( ‘expand_tabs‘,{"set_translate_tabs": True} ) # 转换为空格缩进
class show_overlay_rCommand(sublime_plugin.TextCommand):
def run(self,edit):
window = sublime.active_window()
mark = self.view.sel()[0]
func = self.view.substr( mark )
if func == ‘‘: func=get_word(self.view,mark,‘r‘)
func=reg_function(func,[‘ss‘,‘n‘])
# ctrl+shift+r alt+shift+d 产生序列号http://zhourou.com/mobile/index.php?act=goods&op=goods_detail&goods_id=60&client=wap
class ec_case_lineCommand(sublime_plugin.TextCommand):
def run(self,edit,tr):
json_str=open(v_plug_dir+‘/testone_config.json‘).read()
config_obj_f=json.loads(json_str) # json.dumps(a, ensure_ascii = False))
config_ar=config_obj_f[‘config_ar‘]
self.tr=tr
mark = self.view.sel()[0]
func = self.view.substr( mark )
if func == ‘‘:func=sublime.get_clipboard()
op=False
if self.tr==‘ecp‘: #自动匹配项目 alt+shift+d
# http://zhourou.com/mobile/index.php?act=member_evaluate&op=list&page=10&curpage=1
# func=‘http://www.test5.Com/index.php/Index/get_whois/domain/‘
if re.findall(‘ ‘,func): func=re.compile(r‘[^`]* ([^ ]*)$‘) .sub(r‘\1‘,func)
back=get_xm_type(func)
file=v_test_web+back[0]+‘\\‘
if back[1] == ‘shopnc‘:
file+=re.compile(r‘[\w:/\.]*/(\w*)/index.php[&\w=\?]*‘).sub(r‘\1‘,func)+‘\\‘
file+=‘control\\‘+re.compile(r‘[^`=]*act=(\w*)[&\w=]*‘).sub(r‘\1‘,func)+‘.php‘
if not re.findall(‘&op=‘,func): op=False
op=re.compile(r‘[^`]*&op=(\w*)[&\w=]*‘).sub(r‘\1‘,func)+‘Op‘
if op == ‘Op‘:op=False
elif back[1] == ‘tp‘:
file+=(re.findall(‘system.php‘,func) and ‘Admin‘ or ‘Home‘)+‘\\Lib\\Action\\‘
str_ur=func.replace(‘index.php/‘,‘‘)
str_ur=str_ur.replace(‘//‘,‘‘)
ar=str_ur.split("/")
file+=ar[1]+‘Action.class.php‘
op = ( ar[2] and ar[2] or False)
elif back[1] == ‘ecshop‘:
if re.findall(r‘[\w:/\.]*/(\w+)/[\w]+\.php\??[&\w=]*‘,func):
file+=re.compile(r‘[\w:/\.]*/(\w+)/[\w]+\.php\??[&\w=]*‘).sub(r‘\1‘,func)+‘\\‘
file+=re.compile(r‘[\w:/\.]*/([\w]+\.php)\??[&\w=]*‘).sub(r‘\1‘,func)
if re.findall(r‘[^`]*act=(\w*)[&\w=]*‘,func):
op=re.compile(r‘[^`]*act=(\w*)[&\w=]*‘).sub(r‘\1‘,func)
if not op:
if re.findall(r‘[^`]*step=(\w*)[&\w=]*‘,func):
op=re.compile(r‘[^`]*step=(\w*)[&\w=]*‘).sub(r‘\1‘,func)
self.tr_p=back[1]
else:return
w = sublime.active_window()
if not os.path.isfile(file): # os.path.isfile os.path.exists os.makedirs
if config_ar[0][0]:
file=config_ar[0][0][0]
op=config_ar[0][0][1]
self.tr=config_ar[0][0][2]
self.tr_p=config_ar[0][0][3]
else:
w.run_command( ‘show_overlay‘,{"overlay":"goto","text": ""+file+""} )
return
config_ar[0][0]=[file,op,self.tr,self.tr_p,func]
config_obj_f[‘config_ar‘]=config_ar
open(v_plug_dir+‘/testone_config.json‘,‘w‘).write(json.dumps(config_obj_f, ensure_ascii = False))
view=w.open_file(file, sublime.ENCODED_POSITION )
if not op: return
if not view.is_read_only():
if self.tr==‘ecp‘ and self.tr_p == ‘ecshop‘:
# sublime.set_clipboard(op)
w.run_command( ‘old_case_file_input‘,{"tr":"ec_f","text": ""+op+""} )
return
sh_mark=view.find(op, 0)
if sh_mark.a>-1: view.show(sh_mark)
else:
self.is_read_only(view,op)
def is_read_only(self,view,op):
if view.is_read_only():
sublime.set_timeout(lambda: self.is_read_only( view,op), 500)
return
if self.tr==‘ecp‘ and self.tr_p == ‘ecshop‘:
w = sublime.active_window()
# sublime.set_clipboard(op)
w.run_command( ‘old_case_file_input‘,{"tr":"ec_f","text": ""+op+""} )
return
sh_mark=view.find(op, 0)
# print(sh_mark)
if sh_mark.a>-1: view.show(sh_mark)
# 加在右键菜单里,ecshop原文件 echsopmc原文件
class old_case_fileCommand(sublime_plugin.TextCommand):
def run(self,edit,tr):
w = sublime.active_window()
row=self.view.rowcol(self.view.sel()[0].a)[0]+1
if tr==‘ecshop‘:
strinfo1=re.compile(r‘E:\\\w*\\\w*\\(.*)‘)
file=‘E:\\www\\ecshop\\‘+strinfo1.sub(r‘\1‘,self.view.file_name())
file = file.replace(‘alugzaod‘, ‘admin‘)
elif tr==‘shopc‘:
strinfo1=re.compile(r‘E:\\\w*\\\w*\\(.*)‘)
file=strinfo1.sub(r‘\1‘,file)
file=‘E:\\www\\hunuomall\\‘+file;
elif tr==‘ecshop_pc‘:
file=self.view.file_name().replace(‘\mobile‘, ‘‘)
if os.path.exists(file):w.open_file(file+":"+str(row), sublime.ENCODED_POSITION )
# alt+shift+f
class old_case_file_inputCommand(sublime_plugin.TextCommand):
def run(self,edit,tr,text=‘‘):
print(text)
self.tr=tr
w=sublime.active_window()
if self.tr==‘ec_f‘:
w.show_input_panel("要打开的文件名",text, self.on_pass,self.on_change, None)
else: w.show_input_panel("要打开的文件名","",self.on_done, None, None)
def on_change(self,text):
mark=self.view.sel()[0];
func=‘‘;
for s in text:
func+="["+s.upper()+s.lower()+"]"
regex=[
r"\$_REQUEST\[ ?‘act‘ ?\][^=]*==[^‘\"]*[‘\"]"+func,
r"\$_REQUEST\[ ?‘step‘ ?\][^=]*==[^‘\"]*[‘\"]"+func,
r"\$action[^=]*==[^‘\"]*[‘\"]"+func,
]
for reg in regex:
sh_mark = self.view.find(reg, mark.a)
if sh_mark.a>-1:
self.view.show(sh_mark)
self.view.sel().add( sublime.Region(sh_mark.b-len(text),sh_mark.b))
return
for reg in regex:
sh_mark = self.view.find(reg,0)
if sh_mark.a>-1:
self.view.show(sh_mark)
self.view.sel().add( sublime.Region(sh_mark.b-len(text),sh_mark.b))
return
# print(4354) ($_REQUEST[‘act‘] == ‘afffefe_list‘) \$_REQUEST\[\‘act\‘\] ($_REQUEST[‘act‘] == ‘rwerewfe‘)
def on_done(self,text):
if re.findall(r"^\w:",text) or re.findall(r"^http://",text):
webbrowser.open_new( text )
return
row=self.view.rowcol(self.view.sel()[0].a)[0]+1
if self.tr==‘ecshop‘:
file=nfile=‘E:\\www\\ecshop\\‘;
if re.findall(r"\\",text) or re.findall("/",text):nfile=file+text
elif re.findall(‘.php‘,text):
if os.path.exists(file+text):nfile=file+text
elif os.path.exists(file+‘admin\\‘+text):nfile=file+‘admin\\‘+text
elif re.findall(‘.dwt‘,text):nfile=file+‘themes\\default\\‘+text
elif re.findall(‘.htm‘,text):nfile=file+‘admin\\templates\\‘+text
elif self.tr==‘shopc‘:
file=nfile=‘E:\\www\\hunuomall\\‘;
if re.findall(r"\\",text) or re.findall("/",text):nfile=file+text
elif re.findall(‘.php‘,text):
if os.path.exists(file+text):nfile=file+text
elif os.path.exists(file+‘admin\\‘+text):nfile=file+‘admin\\‘+text
elif re.findall(‘.dwt‘,text):nfile=file+‘themes\\default\\‘+text
elif re.findall(‘.htm‘,text):nfile=file+‘admin\\templates\\‘+text
else: return
if file == nfile:return
if os.path.exists(file+text):
sublime.active_window().open_file(file+":"+str(row), sublime.ENCODED_POSITION )
def on_pass(self,text):
pass
# show_overlay ctrl+f5 ctrl+f6 user.php # 离线版 live
class OpenphpCommand(sublime_plugin.TextCommand):
def run(self, edit, tr = ‘‘):
isHome=isComputerHome()
window = sublime.active_window()
mark = self.view.sel()[0]
if mark.a!=mark.b: func = self.view.substr( mark )
elif tr == ‘cf6‘ : func = get_word(self.view,mark,‘c‘)
else: func = get_word(self.view,mark,‘r‘)
func=reg_function(func,[‘ss‘,‘n‘])
func = func.replace(‘_‘, ‘-‘)
func = func.replace(‘ ‘, ‘‘)
if tr == ‘cf5‘:# php,js
if isHome: #离线版
url_php=v_test_url+‘/shouce/php_manual_zh_review/res/function.‘
url_js =v_test_url+‘/shouce/jquery1.8.3_20121129/‘
f_php=v_test_diru+‘\\shouce\\php_manual_zh_review\\res\\function.‘
f_js =v_test_diru+‘\\shouce\\jquery1.8.3_20121129\\‘
if os.path.exists(f_php+ func + ‘.html‘):
all_url = url_php + func + ‘.html‘
else:
all_url = url_js + func + ‘.html‘
else:# 在线版
url_php =‘http://php.net/manual/zh/function.‘
all_url = url_php + func + ‘.php‘
elif tr == ‘clip‘:# 打开剪贴板里的文件地址
all_url=sublime.get_clipboard()
elif tr == ‘cf6‘:# css
# url=‘http://www.w3school.com.cn/cssref/pr_‘
# if func.startswith(‘font‘):
# func=func.replace(‘-‘,‘_‘)
# elif func.startswith(‘float‘):
# func=‘class_‘+func
# all_url=url+func+‘.asp‘
if isHome:
all_url=‘https://www.baidu.com/s?wd=site%3A%20www.w3school.com.cn%20‘+func
else:
all_url=‘https://www.baidu.com/s?wd=site%3A%20www.w3school.com.cn%20‘+func
elif tr == ‘cf7‘:# html
url=‘http://www.w3school.com.cn/tags/tag_‘
all_url=url+func+‘.asp‘
# pr_pos_vertical-align.asp
# sublime.set_clipboard(all_url)
webbrowser.open_new( all_url )
# alt+f4 alt+f5 ctrl+f1 alt+f1 alt+f2
class open_allCommand(sublime_plugin.TextCommand):
def run(self,edit,tr):
base_dir=v_test_diru+‘\\case\\‘
if tr==‘cf1‘:
file=v_test_dir+‘/test.php‘
file_now=self.view.file_name()
print(file_now)
print(base_dir)
if not file_now == None and not file_now.find(base_dir) == -1:
f=os.path.basename(file_now)
if f.startswith(‘C‘):
file=file_now.replace(f,‘‘)
file+=‘my_case_‘+f[1:][:-3]+‘php‘
sublime.active_window().open_file(file)
return
elif tr==‘af1‘: file=v_test_dir+‘/test.html‘
elif tr==‘af2‘: file=v_test_dir+‘/test.js‘
elif tr==‘af4‘:
file=v_test_url+‘/‘
file_now=self.view.file_name()
if file_now == v_test_diru+‘\\test.html‘:
file=v_test_url+‘/test.html‘
else:
if re.findall(‘extract‘,file_now) or re.findall(‘my_case_‘,file_now):
filePhp=file_now.replace(v_test_diru+‘\\‘,‘‘)
filePhp=filePhp.replace(‘\\‘,‘/‘)
else:filePhp="test.php"
file+=filePhp
file=reg_function(file,[‘ss‘])
elif tr==‘line‘: # alt+f5
mark=self.view.sel()[0]
if mark.a!=mark.b: file =self.view.substr( mark )
else:file = self.view.substr( self.view.line(mark.a) )
row_s=self.view.rowcol(mark.a)[0]
row_e=self.view.rowcol(mark.b)[0]
if row_s==row_e:
file=reg_function(file,[‘ss‘])
if re.findall(‘ ‘,file): file=re.compile(r‘[^`]* ([^ ]*)$‘) .sub(r‘\1‘,file)
if not file == ‘‘ :webbrowser.open_new( file )
return
i=0
import time
while row_s<=row_e:
file = self.view.substr( self.view.line(self.view.text_point(row_s,0)) )
row_s+=1
i+=1
file=reg_function(file,[‘ss‘])
if re.findall(‘ ‘,file): file=re.compile(r‘[^`]* ([^ ]*)$‘) .sub(r‘\1‘,file)
if file == ‘‘ :continue
file = file.replace(‘\t‘,‘‘)
if i> 1:
time.sleep(0.2) #单位秒
sublime.set_timeout(lambda:webbrowser.open_new( file ), 500)
else:
webbrowser.open_new( file )
return
else: file=tr
webbrowser.open_new( file )
class func_tihuan_allCommand(sublime_plugin.TextCommand):
def run(self,edit,tr):
mark = self.view.sel()[0]
func = self.view.substr( mark )
if tr==‘tp‘:
func = func.replace(‘src="img/‘, ‘src="__PUBLIC__/Home/img/‘)
func = func.replace(‘src="images/‘, ‘src="__PUBLIC__/Home/images/‘)
func = func.replace(‘src="js/‘, ‘src="__PUBLIC__/Home/js/‘)
func = func.replace(‘url("../images/‘, ‘url("../images/‘)
func = func.replace(‘url(../images/‘, ‘url(../images/‘)
func = func.replace(‘href="css/‘, ‘href="__PUBLIC__/Home/css/‘)
func = func.replace(‘href="font/‘, ‘href="__PUBLIC__/Home/font/‘)
elif tr==‘tpweb‘:
func = func.replace(‘src="images/‘, ‘src="__PUBLIC__/Home/web/images/‘)
func = func.replace(‘src="js/‘, ‘src="__PUBLIC__/Home/web/js/‘)
func = func.replace(‘url(../images/‘, ‘url(../images/‘)
func = func.replace(‘href="css/‘, ‘href="__PUBLIC__/Home/web/css/‘)
elif tr==‘formatcss‘:
strinfo=re.compile(r‘([^}])\r\s+‘)
strinfo2=re.compile(r‘([^}\n]{4,70})\n‘)
strinfo3=re.compile(r‘([ ]{2,70})‘)
strinfo4=re.compile(r‘(^[ ]{0,70})‘,re.M)
strinfo5=re.compile(r‘\n[ \s]*\n‘)
func=strinfo.sub(r‘\1‘,func)
func=strinfo2.sub(r‘\1‘,func)
func=strinfo3.sub(r‘‘,func)
func=strinfo4.sub(r‘‘,func)
func=strinfo5.sub(r‘\n‘,func)
elif tr==‘tejg‘:
func = func.replace(‘$GLOBALS[\‘db\‘]‘, ‘$db‘)
func = func.replace(‘$GLOBALS[\‘ecs\‘]‘, ‘$ecs‘)
func = func.replace(‘$GLOBALS[\‘_CFG\‘]‘, ‘$_CFG‘)
func = func.replace(‘$GLOBALS[\‘_LANG\‘]‘, ‘$_LANG‘)
func = func.replace(‘$GLOBALS[\‘smarty\‘]->‘, ‘$smarty->‘)
elif tr==‘tezg‘:
func = func.replace(‘$db->‘, ‘$GLOBALS[\‘db\‘]->‘)
func = func.replace(‘$ecs->‘, ‘$GLOBALS[\‘ecs\‘]->‘)
func = func.replace(‘$_CFG‘, ‘$GLOBALS[\‘_CFG\‘]‘)
func = func.replace(‘$_LANG‘, ‘$GLOBALS[\‘_LANG\‘]‘)
func = func.replace(‘$smarty->‘, ‘$GLOBALS[\‘smarty\‘]->‘)
self.view.replace(edit, mark, func);
class write_func_fileCommand(sublime_plugin.TextCommand):
def run(self,edit,func,file,a):
window=sublime.active_window()
show =window.find_open_file(file)
show.insert(edit, a,func)
# show.replace( edit, sublime.Region(0,999999), content)
# ctrl+shift+a ctrl+shift+q ctrl+shift+e 快捷跳转
class all_lineorfile_showCommand(sublime_plugin.TextCommand):
def run(self,edit,tr):
self.tr=tr
self.edit=edit
self.r= get_ar_lsit(self.tr)
i=1
str_arr=[]
for r in self.r:
if i%2==1:str_arr.append(r)
i=i+1
sublime.active_window().show_quick_panel(str_arr,self.select,sublime.MONOSPACE_FONT,1)
def select(self, index):
if index==-1:return
if self.tr == ‘line‘ or self.tr == ‘obj‘ or self.tr == ‘cas‘:
webbrowser.open_new( self.r[index*2+1] )
elif self.tr == ‘code‘:
tr=self.r[index*2+1]
if tr==‘php1‘:
func="/*** 函数名称 \n * @param mixed $info 返回的有效数据集或是错误说明* \n * @param string $msg 为空或是错误类型代号* \n * @param string $result 请求成功或是失败的标识* \n * @param int $post 1为xml方式,2为json方式\n**/\n"
elif tr==‘php2‘:
w=self.view.viewport_extent()[0]
w=int(w/self.view.em_width())-4
func="/*"
while w>0:
func+=‘-‘
w-=1
func+="*/" # 106 53
mark = self.view.sel()[0]
f=self.view.file_name()
sublime.active_window().run_command(‘write_func_file‘,{‘func‘:func,‘file‘:f,‘a‘:mark.a})
def get_ar_lsit(tr):
if tr==‘line‘:
return [
‘文件排序‘,v_test_dir+‘/extract_usort.php‘,
‘testone‘,v_plug_dir+‘/testone.py‘,
‘testone_my_run‘,v_plug_dir+‘/testone_my_run.py‘,
# ‘所见即所得‘,‘E:/1_commonly_used/插件/所见即所得/KindEditor 4.x Documentation.htm‘,
‘所见即所得‘,‘http://wenku.baidu.com/link?url=igmU9ZpJ6_tXv2yUwTmsXNLKd92SQcbCCcUfENKrcHIwDxJU51FgvgVRtCRjv2K0bd09Jdre3wZ0i9BW9IB-sL1WcEZjdd2FT2-oOGuFWRC‘,
‘Validform‘,‘E:/www/mynotes/Uploads/files/889ef93755fe2964c5fbade588a38b98/Validform_v5.3.2/Validform_v5.3.2.js‘,
‘ecshop.txt‘,‘E:/www/mynotes/Uploads/files/6d9857193d663cab6d6aabb851b1b67a/ecshop.txt‘,
‘sublime备份‘,‘E:/www/mynotes/Uploads/files/0447099e1442ae253ca5e7a7a8d75373/‘,
‘ftp备份‘,‘E:/1_commonly_used/sublime/Sublime_Text_Backups‘,
‘navicat_sql‘,‘C:/Users/Administrator/Documents/Navicat/MySQL/servers/127.0.0.1/liudao‘,
‘在线jq库‘,‘http://www.htmleaf.com/js/jquery/jquery-1.8.3.html‘,
‘循环调用php文件‘,v_test_dir+‘/cron.php‘,
‘snippet目录‘,v_plug_dir+"/snippet",
‘sublimeCookie‘,v_test_dir+"/cookie/sublimeCookie.txt",
‘testone_config‘,v_plug_dir+"/testone_config.sublime-settings",
‘testone_config_json‘,v_plug_dir+"/testone_config.json",
‘curl_uu‘,v_test_dir+"/curl_uu.php",
‘AllAction.class.php‘,v_test_dir+"/lib/thinkphp/AllAction.class.php",
]
elif tr==‘obj‘:
f_dir=v_test_dir+‘/sublime/‘
file_ar=os.listdir(f_dir)
arr=[]
for f in file_ar:
aa=re.findall(r‘^(\w+).([^^]+)‘,f)
if aa[0][1] == ‘sublime-workspace‘:continue
arr.append(aa[0][0])
arr.append(f_dir+f)
return arr
elif tr==‘cas‘:
f_dir=v_test_dir+‘/case/‘
file_ar=os.listdir(f_dir)
arr=[]
for f in file_ar:
is_break=False
for fi in os.listdir(f_dir+f+‘/‘):
if is_break: break
if not fi.startswith(‘C‘):continue
arr.append(fi[1:-4])
arr.append(f_dir+f+‘/‘+fi)
is_break=True
return arr
elif tr==‘code‘:
return [‘php函数注释‘,‘php1‘,
‘横线‘,‘php2‘,
]
elif tr==‘ay‘:
return [
]
# ctrl+shift+y // 循环调用网络链接
class test_cronCommand(sublime_plugin.TextCommand):
def run(self,edit):
self.url=v_test_url+‘/cron.php‘
thread = PrefixrApiCall(self.url)
thread.start()
self.handle_threads(thread)
def handle_threads(self,thread, i=0, dir=1, f=1):
before = i % 8
after = (7) - before
if not after: dir = -1
if not before:dir = 1
i += dir
if thread.is_alive():
self.view.set_status(‘prefixr‘, ‘正在联网_‘+ str(f) +‘ [%s=%s]‘% (‘ ‘ * before, ‘ ‘ * after))
sublime.set_timeout(lambda: self.handle_threads( thread, i, dir,f ), 1000)
return
try: a=thread.result.decode(‘utf-8‘)
except UnicodeDecodeError as e: a=‘{"status": 0, "message":"格式转换失败"}‘
ob=json.loads(a) # json.dumps(a, ensure_ascii = False))
if ob[‘status‘] == 0 and f < 100000:
f=f+1
if ob[‘message‘] != ‘‘:print(ob[‘message‘])
thread = PrefixrApiCall(self.url)
thread.start()
self.view.set_status(‘prefixr‘, ‘正在联网_‘+ str(f) +‘ [%s=%s]‘% (‘ ‘ * before, ‘ ‘ * after))
sublime.set_timeout(lambda: self.handle_threads( thread, i, dir,f ), 1000)
return
sublime.message_dialog(‘运行结束了:‘+ob[‘message‘])
self.view.erase_status(‘prefixr‘)
# ctrl+f4 alt+f8 ctrl+u E:\www\mynotes\test\case\my_case_zhourou.php
class open_browser_backphpCommand(sublime_plugin.TextCommand):
def run(self,edit,tr):
json_str=open(v_plug_dir+‘/testone_config.json‘).read()
config_obj_f=json.loads(json_str) # json.dumps(a, ensure_ascii = False))
config_ar=config_obj_f[‘config_ar‘]
if tr==‘uu‘: # ctrl+u
file_now=self.view.file_name()
url=v_test_url+‘/curl_uu.php?‘;
bb=re.findall(r‘(\w+)\\(.+)‘,file_now.replace(‘E:\www\\‘,‘‘))
if bb and bb[0][0]:
url+=‘case=‘+bb[0][0]+‘&file=‘+file_now.replace(‘\\‘,‘/‘);
else:return
elif tr==‘su‘: # ctrl+f4
sublimeAu=‘// sublimeAutoTimeLastSyn‘
mark= self.view.find(sublimeAu, 0)
if mark.a > 0: # 自动添加处理的时间
import time
time_str=‘$time_str=\‘‘+time.strftime("%Y/%m/%d %H:%M:%S")+‘\‘;\n‘+sublimeAu;
self.view.replace(edit, mark, time_str);
sublime.set_timeout(lambda: self.view.run_command(‘save‘), 10)
func = self.view.substr( self.view.sel()[0] )
url=v_test_url+‘/‘
base_dir=v_test_diru+‘\\‘
filePhp=‘test.php‘
file_now=self.view.file_name()
if file_now:
if not file_now.find(base_dir) == -1:
f=os.path.basename(file_now)
if f.startswith(‘extract‘) or f.startswith(‘my_case_‘):
filePhp=file_now.replace(base_dir,‘‘)
filePhp=filePhp.replace(‘\\‘,‘/‘)
if not self.view.find(‘new contrastFile‘, 0).a == -1:webbrowser.open_new( v_svn_dir )
if func != ‘‘: filePhp=func
url+=filePhp
elif tr==‘jt‘:# alt+f8
sublime.active_window().run_command( ‘save‘ )
url=sublime.get_clipboard()
if not url.find(‘http‘):url+‘http://‘
if re.findall(‘ ‘,url): url=re.compile(r‘[^`]* ([^ ]*)$‘).sub(r‘\1‘,url)
try:
urllib.request.urlopen(urllib.request.Request(url))
except :
sublime.status_message(‘ 无效的网页! ‘)
if config_ar[1][0]:
url=config_ar[1][0]
else:
sublime.status_message(‘ 无有效的网页记录! ‘)
return
config_ar[1][0]=url
elif tr==‘jt9‘:# alt+f9
text=‘‘
resub=re.compile(r‘[^\\]*\\[^\\]*\\[^\\]*\\[^\\]*\\[^\\]*\\([^\\]*)\\[^\\]*‘);
run_view=None
for view in sublime.active_window().views():
func=view.file_name()
if func:
xm=resub.sub(r‘\1‘,func)
if(len(xm)<len(func)):
xm=xm[xm.find(‘_‘) + 1:]
if func.endswith(xm+‘.txt‘):
run_view=view
if run_view:
mark=run_view.find(‘test_url:‘,0)
if mark.a != -1:
row_s=run_view.rowcol(mark.a)[0]
line=run_view.substr( run_view.line(run_view.text_point(row_s,0)) )
if re.findall(‘ ‘,line): line=re.compile(r‘[^`]* ([^ ]*)$‘) .sub(r‘\1‘,line)
url=line
else:return
mark=run_view.find(‘test_auto_var_dump:‘,0)
auto_var_dump=0
if mark.a != -1:
auto_var_dump=run_view.substr( sublime.Region(mark.b,mark.b+1) )
if auto_var_dump:
mark=self.view.find(‘test_auto_var_dump‘,0)
auto_var_dump=0
if mark.a != -1:
row_s=self.view.rowcol(mark.a)[0]+1
star=self.view.text_point(row_s,0)
mark_all=sublime.Region(star,star+1)
line=self.view.substr( self.view.line( star ) )
i=1
add=False
if re.findall(r‘^[ \s]*// ‘,line) == []:add=True
while line.find(‘die(‘) == -1 and i<20:
row_s+=1
mark_tmp=self.view.line(self.view.text_point(row_s,0))
mark_all.b=mark_tmp.b
line = self.view.substr( mark_tmp )
i+=1
func = self.view.substr( mark_all )
if not add:
strinfo1=re.compile(r‘^([ \s]*)// (.*)‘,re.M)
func=strinfo1.sub(r‘\1\2‘,func)
self.view.replace(edit, mark_all, func);
sublime.set_timeout(lambda: self.view.run_command(‘save‘), 10)
self.mark_all=mark_all
auto_var_dump=1
self.auto_var_dump=auto_var_dump
# return
else:return
config_obj_f[‘config_ar‘]=config_ar
open(v_plug_dir+‘/testone_config.json‘,‘w‘).write(json.dumps(config_obj_f, ensure_ascii = False))
self.view.set_status(‘url‘, url)
self.tr=tr
# cmd
# cmdFile=‘E:/phpStudy/php52/php.exev_test_dir+ /test.php‘;
# import subprocess
# output = subprocess.check_output(cmdFile, shell=True)
# output=output.decode(‘gbk‘)
# print(output)
# 网络
thread = PrefixrApiCall(url,‘html‘)
if tr==‘jt9‘:# alt+f9
sublime.set_timeout(lambda: thread.start(), 11)
sublime.set_timeout(lambda: self.handle_threads(thread), 12)
else:
thread.start()
self.handle_threads(thread)
def handle_threads(self, thread, i=0, dir=1 ):
before = i % 8
after = (7) - before
if not after: dir = -1
if not before: dir = 1
i += dir
if thread.is_alive():
self.view.set_status(‘prefixr‘, ‘Prefixr [%s=%s]‘% (‘ ‘ * before, ‘ ‘ * after))
sublime.set_timeout(lambda: self.handle_threads( thread, i, dir ), 100)
return
self.view.erase_status(‘prefixr‘)
try: content=thread.result.decode(‘utf-8‘)
except :
try: content=thread.result.decode(‘gbk‘)
except :
print(thread.result)
content=‘编码错误‘
try:
b_json=json.loads(content)
b_json=json.dumps(b_json,ensure_ascii=False,sort_keys=True, indent=2)
except :
b_json=content
w = sublime.active_window()
config_obj= sublime.load_settings("testone_config.sublime-settings")
config_ar_panel=config_obj.get("config_ar_panel")
config_ar_panel[1]=0
config_obj.set("config_ar_panel", config_ar_panel)
r=w.create_output_panel("expec")
r.settings().set("word_wrap", True)
r.run_command(‘append‘, {‘characters‘: b_json, ‘force‘: True, ‘scroll_to_end‘: True})
r.show(0)
w.run_command("show_panel", {"panel": "output.expec"})
if self.tr == ‘jt9‘ and self.auto_var_dump:
mark_all=self.mark_all
row_s=self.view.rowcol(mark_all.a)[0]
line=self.view.substr( self.view.line( mark_all.a ) )
i=1
while line.find(‘die(‘) == -1 and i<20:
row_s+=1
mark_tmp=self.view.line(self.view.text_point(row_s,0))
mark_all.b=mark_tmp.b
line = self.view.substr( mark_tmp )
i+=1
func = self.view.substr( mark_all )
# print(mark_all)
# print(func)
strinfo1=re.compile(r‘^([ \s]*)([^ \s]*)‘,re.M)
func=strinfo1.sub(r‘\1// \2‘,func)
# print(func)
sublime.active_window().run_command("autoeidtview", {"mark_all_a": mark_all.a, "mark_all_b": mark_all.b, "func": func})
sublime.set_timeout(lambda: self.view.erase_status(‘url‘), 4000)
class autoeidtviewCommand(sublime_plugin.TextCommand):
def run(self,edit,mark_all_a=1,mark_all_b=1,func=2):
self.view.replace(edit, sublime.Region(mark_all_a,mark_all_b), func);
sublime.set_timeout(lambda: self.view.run_command(‘save‘), 10)
class PrefixrApiCall(threading.Thread):
def __init__(self,url,tr=‘json‘):
self.url = url
self.result = ‘‘
self.tr = tr
threading.Thread.__init__(self)
def run(self):
import http.cookiejar
import urllib.parse
import urllib.error
tr=self.tr
cookie_filename = v_plug_dir+‘/file/sublimeCookie.txt‘
is_cookie=os.path.isfile(cookie_filename)
cookie = http.cookiejar.MozillaCookieJar(cookie_filename)
# FileCookieJar(filename):创建FileCookieJar实例,检索cookie信息并将信息存储到文件中,filename是文件名。
# MozillaCookieJar(filename):创建与Mozilla cookies.txt文件兼容的FileCookieJar实例。
# LWPCookieJar(filename):创建与libwww-perl Set-Cookie3文件兼容的FileCookieJar实例。
from http import cookies
if is_cookie:
cookie.load(cookie_filename, ignore_discard=True, ignore_expires=True)
openner=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie))
try:
# values={‘key‘:‘c1f788906bea5f0e8751786db0660fba‘,‘rr‘:‘555‘}
# data=urllib.parse.urlencode(values).encode(‘utf-8‘)
headers={ ‘User-Agent‘ : ‘Mozilla/4.0 (compatible; MSIE5.5; Windows NT)‘}
text=open(v_plug_dir+‘/file/0.txt‘).read()
text=reg_function(text,[‘ss‘,‘l‘,‘n‘])
data=text.encode(‘utf-8‘)
# 转换编码
# self.url=self.url.replace(‘http://‘,‘‘)
# self.url=urllib.parse.quote(self.url)
# self.url=‘http://‘+self.url
response=openner.open(self.url,data)
self.result=response.read()
# data=urllib.parse.urlencode(values).encode(‘utf-8‘)
# response=urllib.request.urlopen(urllib.request.Request(self.url, data, headers))
# self.result=response.read()
except urllib.error.HTTPError as e : # except urllib.error.HTTPError as e:
print(self.result)
if tr==‘json‘: self.result = ‘{"status": 0, "message":"网络获取失败"}‘.encode(‘utf-8‘)
else: self.result = ‘页面错误‘.encode(‘utf-8‘)
cookie.save(ignore_discard=True, ignore_expires=True) # 保存cookie到cookie.txt中
return
# ctrl+i
class my_incremental_findCommand(sublime_plugin.TextCommand):
def run(self,edit):
window = sublime.active_window()
# pt = self.view.text_point(line, 0)
# self.view.sel().clear()
# self.view.sel().add(sublime.Region(pt-66,pt))
# self.view.show(pt)
# self.view.find(func, mark.a-1)
# mark = self.view.sel()[0]
# func = self.view.substr( mark )
# func=‘view‘
# print(mark)
# self.view.add_regions("mark2", [mark], "comment",‘bookmark‘,sublime.DRAW_OUTLINED|sublime.PERSISTENT)
# "toggle": True, "reverse": True, "regex":False ,"where" reverse [Bool]:在缓冲区中是否后向搜索内容。 toggle [Bool]: 当面板已经可见时,是否隐藏面板
window.run_command( ‘show_panel‘, {"panel": "incremental_find", "reverse": False, "regex":False,"toggle":False,"whole_word":False,"case_sensitive":False,"inselecttion":True} )
# mark_line=[self.view.line(mark[0].a)]
# mark_line[0].b=mark_line[0].b+156;
# self.view.add_regions("mark", mark_line, "comment",‘bookmark‘,sublime.DRAW_OUTLINED|sublime.PERSISTENT)
# print(mark)
# m=self.view.expand_by_class(mark, sublime.CLASS_WORD_START|sublime.CLASS_WORD_END, "[]{}()<>:.")
# print(m)
# window.run_command( ‘show_panel‘, {"panel": "incremental_find", "reverse": True} )
# { "keys": ["ctrl+i"], "command": "show_panel", "args": {"panel": "incremental_find", "reverse": true} },
# self.view.erase_regions("mark")
# v.expand_by_class(pt, sublime.CLASS_WORD_START | sublime.CLASS_WORD_END, "[]{}()<>:.")
# expand_by_class(point, classes, <separators>)
# window = sublime.active_window()
# mark = self.view.sel()[0]
# func = self.view.substr( mark )
# if func == ‘‘:
# mark_line=self.view.line(mark.a)
# mark.b=mark_line.b;
# mark_line.b= mark.a
# func_a = self.view.substr( mark_line )
# func_b = self.view.substr( mark )
# back_b=re.findall(r‘(^[\w_]+)[\"\‘\(]‘,func_b)
# back_a=re.findall(r‘[\"\‘>\.\s]([\w_]+)$‘,func_a)
# if back_a :
# func= back_a[0]
# if back_b :
# func+= back_b[0]
# if func.find(‘\‘‘)==-1 or func.find(‘"‘)==-1:
# func=‘‘
# window = sublime.active_window()
# file=‘D:/Program Files\Sublime Text 3/Data/Packages/User\show.html‘
# show =window.find_open_file(file)
# if show:
# window.focus_view(show)
# window.run_command( ‘save‘ )
# window.run_command( ‘close‘ )
# else:
# window.run_command( ‘close‘ )
# url = self.view.file_name()
# if url and url.endswith(‘show.html‘):
# else:
# window.run_command( ‘close‘ )
# 更新插件包
# import urllib.request,os;
# pf = ‘Package Control.sublime-package‘;
# ipp = sublime.installed_packages_path();
# urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) );
# # open(os.path.join(ipp, pf), ‘wb‘).write(urllib.request.urlopen( ‘http:/\sublime.wbond.net/‘ + pf.replace(‘ ‘,‘%20‘)).read())
# ([^}])\r\s+
# ([^}\n]{4,70})\n
# re_cdata=re.compile(‘//<!
# CDATA/[[>]∗//
# /]>‘,re.I) #匹配CDATA
# re_script=re.compile(‘<\s*script[^>]*>[^<]*<\s*/\s*script\s*>‘,re.I)#Script
# re_style=re.compile(‘<\s*style[^>]*>[^<]*<\s*/\s*style\s*>‘,re.I)#style
# re_br=re.compile(‘<br\s*?/?>‘)#处理换行
# re_h=re.compile(‘</?/w+[^>]*>‘)#HTML标签
# re_comment=re.compile(‘<!--[^>]*-->‘)#HTML注释
#
# s=re_cdata.sub(‘‘,htmlstr)#去掉CDATA
# s=re_script.sub(‘‘,s) #去掉SCRIPT
# s=re_style.sub(‘‘,s)#去掉style
# s=re_br.sub(‘\n‘,s)#将br转换为换行
# s=re_h.sub(‘‘,s) #去掉HTML 标签
# s=re_comment.sub(‘‘,s)#去掉HTML注释
# #去掉多余的空行
# blank_line=re.compile(‘\n+‘)
# s=blank_line.sub(‘\n‘,s)
# s=replaceCharEntity(s)#替换实体
# return s
# self.view.insert(edit, 0, "Hellrereo, World!")
# open_file
# PS:如果要指定用什么浏览器预览,也可以将最后一行代码改成这样:
# webbrowser.get(‘safari‘).open_new(url)
# import time
# class ShowTimeInStatusCommand(sublime_plugin.TextCommand):
# def run(self, edit):
# # view.set_status(‘time_msg‘, ‘ 当前时间:‘+datetime.datetime.now())
# sublime.status_message(‘ 当前时间:‘+time.strftime("%Y-%m-%d %H:%M:%S"))
# 使用cmd命令
# import subprocess
# output = subprocess.check_output(‘dir‘, shell=True)
# output=output.decode(‘gbk‘)
# print(output)
# 字符串分割成数组,数组合并成字符串
# m = u‘我 们都是 中国人‘
# ar=m.split(" ")
# gg=",".join(ar)s
# 查找边界
# line_text.endswith(‘my_case_‘):
# line_text.startswith(‘my_case_‘)
# 查找子字符串
# url.find(‘show)
# 文字提取
# re.compile(r‘\s+(\d+):.*‘).sub(r‘\1‘,line_text) # 直接截取,截取不到也会返回字符串
# 字符串替换
# func=func.replace(‘-‘,‘_‘)
# 去空格及特殊符号
# s.strip().lstrip().rstrip(‘,‘)
# 复制字符串
# #strcpy(sStr1,sStr2)
# sStr1 = ‘strcpy‘
# sStr2 = sStr1
# sStr1 = ‘strcpy2‘
# print sStr2
# 连接字符串
# #strcat(sStr1,sStr2)
# sStr1 = ‘strcat‘
# sStr2 = ‘append‘
# sStr1 += sStr2
# print sStr1
# 查找字符
# #strchr(sStr1,sStr2)
# # < 0 为未找到
# sStr1 = ‘strchr‘
# sStr2 = ‘s‘
# nPos = sStr1.index(sStr2)
# print nPos
# 比较字符串
# #strcmp(sStr1,sStr2)
# sStr1 = ‘strchr‘
# sStr2 = ‘strch‘
# print cmp(sStr1,sStr2)
# 扫描字符串是否包含指定的字符
# #strspn(sStr1,sStr2)
# sStr1 = ‘12345678‘
# sStr2 = ‘456‘
# #sStr1 and chars both in sStr1 and sStr2
# print len(sStr1 and sStr2)
# 字符串长度
# #strlen(sStr1)
# sStr1 = ‘strlen‘
# print len(sStr1)
# 将字符串中的大小写转换
# #strlwr(sStr1)
# sStr1 = ‘JCstrlwr‘
# sStr1 = sStr1.upper()
# #sStr1 = sStr1.lower()
# print sStr1
# 追加指定长度的字符串
# #strncat(sStr1,sStr2,n)
# sStr1 = ‘12345‘
# sStr2 = ‘abcdef‘
# n = 3
# sStr1 += sStr2[0:n]
# print sStr1
# 字符串指定长度比较
# #strncmp(sStr1,sStr2,n)
# sStr1 = ‘12345‘
# sStr2 = ‘123bc‘
# n = 3
# print cmp(sStr1[0:n],sStr2[0:n])
# 复制指定长度的字符
# #strncpy(sStr1,sStr2,n)
# sStr1 = ‘‘
# sStr2 = ‘12345‘
# n = 3
# sStr1 = sStr2[0:n]
# print sStr1
# 将字符串前n个字符替换为指定的字符
# #strnset(sStr1,ch,n)
# sStr1 = ‘12345‘
# ch = ‘r‘
# n = 3
# sStr1 = n * ch + sStr1[3:]
# print sStr1
# 扫描字符串
# #strpbrk(sStr1,sStr2)
# sStr1 = ‘cekjgdklab‘
# sStr2 = ‘gka‘
# nPos = -1
# for c in sStr1:
# if c in sStr2:
# nPos = sStr1.index(c)
# break
# print nPos
# 翻转字符串
# #strrev(sStr1)
# sStr1 = ‘abcdefg‘
# sStr1 = sStr1[::-1]
# print sStr1
# 查找字符串
# #strstr(sStr1,sStr2)
# sStr1 = ‘abcdefg‘
# sStr2 = ‘cde‘
# print sStr1.find(sStr2)
# 分割字符串
# #strtok(sStr1,sStr2)
# sStr1 = ‘ab,cde,fgh,ijk‘
# sStr2 = ‘,‘
# sStr1 = sStr1[sStr1.find(sStr2) + 1:]
# print sStr1
# #或者
# s = ‘ab,cde,fgh,ijk‘
# print(s.split(‘,‘))
# 连接字符串
# delimiter = ‘,‘
# mylist = [‘Brazil‘, ‘Russia‘, ‘India‘, ‘China‘]
# print delimiter.join(mylist)
# PHP 中 addslashes 的实现
# def addslashes(s):
# d = {‘"‘:‘\\"‘, "‘":"\\‘", "\0":"\\\0", "\\":"\\\\"}
# return ‘‘.join(d.get(c, c) for c in s)
# s = "John ‘Johny‘ Doe (a.k.a. \"Super Joe\")\\\0"
# print s
# print addslashes(s)
# 只显示字母与数字
# def OnlyCharNum(s,oth=‘‘):
# s2 = s.lower();
# fomart = ‘abcdefghijklmnopqrstuvwxyz0123456789‘
# for c in s2:
# if not c in fomart:
# s = s.replace(c,‘‘);
# return s;
# print(OnlyStr("a000 aa-b"))
# 截取字符串
# str = ’0123456789′
# print str[0:3] #截取第一位到第三位的字符
# print str[:] #截取字符串的全部字符
# print str[6:] #截取第七个字符到结尾
# print str[:-3] #截取从头开始到倒数第三个字符之前
# print str[2] #截取第三个字符
# print str[-1] #截取倒数第一个字符
# print str[::-1] #创造一个与原字符串顺序相反的字符串
# print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
# print str[-3:] #截取倒数第三位到结尾
# print str[:-5:-3] #逆序截取,具体啥意思没搞明白?
# import socket
# #获取本机电脑名
# myname = socket.getfqdn(socket.gethostname( ))
# #获取本机ip
# myaddr = socket.gethostbyname(myname)
# print (myname)
# print (myaddr)
# return
# localIP = socket.gethostbyname(socket.gethostname())#这个得到本地ip
# print ("local ip:%s "%localIP)
# return
# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# try:
# s.connect((‘10.255.255.255‘, 0))
# IP = s.getsockname()[0]
# except:
# IP = ‘127.0.0.1‘
# finally:
# s.close()
# print(IP)
# return IP
import sublime, sublime_plugin, datetime
import webbrowser
import re
import urllib.request,os
import threading
import json
import sublime_api
import sys
# 通用的参数设置
# sublime.packages_path()
v_test_url=‘http://mynotes.com/test‘
v_test_dir=‘E:/www/mynotes/test‘
v_test_diru=v_test_dir.replace(‘/‘,‘\\\\‘)
v_svn_dir=‘E:\文件导出\contraSaver‘
v_plug_dir=‘D:/Program Files/Sublime Text 3/Data/Packages/SubPhp‘
# 公司电脑: USER-20160705YG 家里电脑: FBLCOWTLBYZQU6Q
def isComputerHome():
if getComputerName() == ‘FBLCOWTLBYZQU6Q‘:
isHome=True
else:
isHome=False
return isHome
# 获取当前电脑名称
def getComputerName(ComputerName=[]):
if ComputerName !=[]:
return ComputerName[0]
else:
import socket
Name = socket.getfqdn(socket.gethostname( ))
ComputerName.append(Name)
return Name
def get_word(view,mark,type_r,one=True):
func=‘‘
mark_line=view.line(mark.a)
func_a = view.substr( sublime.Region(mark_line.a,mark.a) )
func_b = view.substr( sublime.Region(mark.a,mark_line.b) )
if type_r == ‘r‘: # 获取单词的正则 函数 方法名
back_a=re.findall(r‘([\w_]+)$‘,func_a)
back_b=re.findall(r‘(^[\w_]+)[\(\"\‘>\.\s=:]?‘,func_b)
elif type_r == ‘w‘: # 获取单词的正则 文件名
back_a=re.findall(r‘[\)\"\‘>\s=:]?([\w_/\\]+)$‘,func_a)
back_b=re.findall(r‘(^[\w_\./\\]+)[\(\"\‘>\s=:]?‘,func_b)
else:
back_b=re.findall(r‘(^[\w_]+)[\"\‘\(]‘,func_b)
back_a=re.findall(r‘[\"\‘>\.\s]([\w_]+)$‘,func_a)
if one:
if back_a and back_b: func = back_a[0] + back_b[0]
else:
if back_a : func= back_a[0]
if back_b : func+= back_b[0]
return func
def reg_function(func,type_r):
if func == ‘‘: return ‘‘
for t in type_r:
if t==‘n‘:
strinfo=re.compile(r‘\n‘,re.M)
func=strinfo.sub(r‘‘,func)
if t==‘ss‘:
strinfo=re.compile(r‘^[ \s]*‘,re.M)
func=strinfo.sub(r‘‘,func)
if t==‘l‘: # 空行
strinfo=re.compile(r‘\n[ \s]*\n‘)
func=strinfo.sub(r‘\n‘,func)
return func
# ctrl+s
class my_saveCommand(sublime_plugin.TextCommand):
def run(self,edit,text=‘‘):
if not self.view.file_name():
config_obj= sublime.load_settings("testone_config.sublime-settings")
config_ar_panel=config_obj.get("config_ar_panel")
if config_ar_panel[1] == 9:
open(v_plug_dir+‘/file/sublimeCookie.txt‘,‘w‘).write(self.view.substr( sublime.Region(0,self.view.size()) ))
else:
open(v_plug_dir+‘/file/‘+str(config_ar_panel[1])+‘.txt‘,‘w‘).write(self.view.substr( sublime.Region(0,self.view.size()) ))
else:
sublime.active_window().run_command(‘save‘)
class my_new_fileCommand(sublime_plugin.TextCommand):
def run(self,edit,text=‘‘):
view=sublime.active_window().new_file()
for mark in self.view.sel():
text+=self.view.substr(mark)+‘\n\n‘
view.insert(edit,0,text)
class my_delete_fileCommand(sublime_plugin.TextCommand):
def run(self,edit):
w=sublime.active_window();
file=self.view.file_name();
if os.path.isfile(file):
os.remove(file)
w.run_command(‘close‘);
# ctrl+1 ctrl+2 ctrl+3 ctrl+4 ctrl+5 ctrl+6 ctrl+7 ctrl+8 ctrl+9
class my_create_output_panelCommand(sublime_plugin.TextCommand):
def run(self,edit,index=1,text=‘‘):
config_obj= sublime.load_settings("testone_config.sublime-settings")
config_ar_panel=config_obj.get("config_ar_panel")
w = sublime.active_window()
r=w.create_output_panel("expec")
r.settings().set("file_name", ‘erfewre‘)
r.settings().set("word_wrap", True)
if index==8:
for view in sublime.active_window().views():
name=view.file_name()
if name:
text+=view.file_name()+‘\n‘
elif index == 7:
text=self.view.file_name()+‘\n‘
elif index == 9:
text=open(v_plug_dir+‘/file/sublimeCookie.txt‘).read()
else:
text=open(v_plug_dir+‘/file/‘+str(index)+‘.txt‘).read()
# elif index <= 2 or index == 9:
# text=open(v_plug_dir+‘/file/‘+str(index)+‘.txt‘).read()
# else:
# if config_ar_panel[0][index]:
# text=config_ar_panel[0][index]
config_ar_panel[1]=index
r.run_command(‘append‘, {‘characters‘: text, ‘force‘: True, ‘scroll_to_end‘: True})
r.show(0)
w.run_command("show_panel", {"panel": "output.expec"})
config_obj.set("config_ar_panel", config_ar_panel)
# show_overlay ctrl+p ctrl+r
class my_show_overlayCommand(sublime_plugin.TextCommand):
def run(self,edit,tr):
w=sublime.active_window()
mark = self.view.sel()[0]
func = self.view.substr( mark )
if func == ‘‘:
type_r=‘r‘
if tr==‘cp‘: type_r=‘w‘
func=get_word(self.view,mark,type_r)
if tr==‘cp‘ and func.find(‘.‘)==-1: func=‘‘
func=reg_function(func,[‘ss‘,‘n‘])
if tr==‘cp‘:w.run_command( ‘show_overlay‘,{"overlay":"goto","text": ""+func+""} )
if tr==‘cr‘:w.run_command( ‘show_overlay‘,{"overlay":"goto","text": "@"+func+""} )
# ctrl+f
class my_ctrl_fCommand(sublime_plugin.TextCommand):
def run(self, edit, forward = True, sub_words = False):
config_obj= sublime.load_settings("testone_config.sublime-settings")
config_ar_panel=config_obj.get("config_ar_panel")
config_ar_panel[1]=0
window = sublime.active_window()
window.run_command( ‘show_panel‘,{"panel": "find", "reverse": False} )
config_obj.set("config_ar_panel", config_ar_panel)
# ctrl+shift+f
class my_ctrl_shift_fCommand(sublime_plugin.TextCommand):
def run(self, edit, forward = True, sub_words = False):
config_obj= sublime.load_settings("testone_config.sublime-settings")
config_ar_panel=config_obj.get("config_ar_panel")
config_ar_panel[1]=0
window = sublime.active_window()
window.run_command( ‘show_panel‘,{"panel": "find_in_files"} )
config_obj.set("config_ar_panel", config_ar_panel)
# ctrl+w
class my_closeCommand(sublime_plugin.TextCommand):
def run(self,edit):
sublime.active_window().run_command( ‘close‘ )
# ctrl+/ 多加一个 bat 的注释
class my_toggle_commentCommand(sublime_plugin.TextCommand):
def run(self,edit):
window = sublime.active_window()
file=self.view.file_name()
if re.findall(r".bat$",file) :
for mark in self.view.sel():
lines=self.view.lines(mark)
add=False
i=1
for mark_one in lines:
if i == 1:mark.a=mark_one.a
i=i+1
mark.b=mark_one.b
if add:continue
func_line = self.view.substr( mark_one )
if re.findall(r‘^[ \s]*$‘,func_line):continue
if re.findall(r‘^[ \s]*rem ‘,func_line) == []:add=True
func = self.view.substr( mark )
if add:
strinfo1=re.compile(r‘^([ \s]*)([^ \s]*)‘,re.M)
func=strinfo1.sub(r‘\1rem \2‘,func)
else:
strinfo1=re.compile(r‘^([ \s]*)rem (.*)‘,re.M)
func=strinfo1.sub(r‘\1\2‘,func)
self.view.replace(edit, mark, func);
else: window.run_command( ‘toggle_comment‘,{ "block": False })
标签:
原文地址:http://www.cnblogs.com/flyskycode/p/5789373.html