3 Star 6 Fork 1

lonewolf / pythonDev

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
python.py 6.88 KB
一键复制 编辑 原始数据 按行查看 历史
lonewolf 提交于 2014-10-28 19:58 . init
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: lonewolf
# Date: 2013-10-26 11:23:48
#
import sublime
import sublime_plugin
import functools
import os
import datetime
import re
import time
import json
try:
import helper
import template
import rebuild
except ImportError:
from . import helper
from . import template
from . import rebuild
# 当前文件路径
CUR_PATH = os.path.dirname(os.path.realpath(__file__))
# 存放临时文件的地址
TEMP_PATH=""
# 用户定义信息文件,用于跳转
USER_DEFINITION_LIST=[]
# init plugin,load definitions
def init():
global TEMP_PATH,USER_DEFINITION_LIST
TEMP_PATH=sublime.packages_path()+"/User/pythonDev.cache"
path=os.path.join(TEMP_PATH,"user_definition.json")
if os.path.exists(path):
USER_DEFINITION_LIST=json.loads(helper.readFile(path))
# 新建一个py文件
class PythonNewFileCommand(sublime_plugin.WindowCommand):
def run(self, dirs):
self.window.run_command("hide_panel")
title = "untitle"
on_done = functools.partial(self.on_done, dirs[0])
v = self.window.show_input_panel(
"File Name:", title + ".py", on_done, None, None)
v.sel().clear()
v.sel().add(sublime.Region(0, len(title)))
def on_done(self, path, name):
filePath = os.path.join(path, name)
if os.path.exists(filePath):
sublime.error_message("Unable to create file, file exists.")
else:
code = template.pyTemplate
# add attribute
settings = helper.loadSettings("pythonDev")
format = settings.get("date_format", "%Y-%m-%d %H:%M:%S")
date = datetime.datetime.now().strftime(format)
code = code.replace("${date}", date)
author=settings.get("author", "Your Name")
code = code.replace("${author}", author)
# save
helper.writeFile(filePath, code)
v=sublime.active_window().open_file(filePath)
# cursor
v.run_command("insert_snippet",{"contents":code})
sublime.status_message("Python file create success!")
def is_enabled(self, dirs):
return len(dirs) == 1
# 新建一个空的__init__.py文件
class PythonCreateInitFileCommand(sublime_plugin.WindowCommand):
def run(self, dirs):
filePath = os.path.join(dirs[0], "__init__.py")
helper.writeFile(filePath, "")
sublime.status_message("__init__.py create success!")
def is_enabled(self, dirs):
return len(dirs) == 1
# 更正缩进,tab->四个空格
class PythonCorrectIndentCommand(sublime_plugin.TextCommand):
def run(self,edit):
region=sublime.Region(0,self.view.size())
text=self.view.substr(region)
arr=text.split("\n")
for i in range(0,len(arr)):
line=arr[i]
m=re.match("^(\s+)(.*)$",line)
if m:
a=re.sub("\t"," ",m.group(1))
arr[i]=a+m.group(2)
text="\n".join(arr)
self.view.replace(edit, region,text)
def is_visible(self):
return helper.checkFileExt(self.view.file_name(),"py")
# 右键跳转到定义
class PythonGotoDefinitionCommand(sublime_plugin.TextCommand):
def run(self, edit):
# select text
sel=self.view.substr(self.view.sel()[0])
if len(sel)==0:
return
# find all match file
matchList=[]
showList=[]
for item in USER_DEFINITION_LIST:
if item[0]==sel:
matchList.append(item)
showList.append(item[1])
if len(matchList)==0:
sublime.status_message("Can not find definition '%s'"%(sel))
elif len(matchList)==1:
filepath=matchList[0][2]
if os.path.exists(filepath):
self.view.window().open_file(filepath+":"+str(matchList[0][3]),sublime.ENCODED_POSITION)
else:
sublime.status_message("%s not exists"%(filepath))
else:
# multi match
self.matchList=matchList
on_done = functools.partial(self.on_done)
self.view.window().show_quick_panel(showList,on_done)
def on_done(self,index):
if index==-1:
return
item=self.matchList[index]
filepath=item[2]
filepath=os.path.abspath(filepath)
if os.path.exists(filepath):
self.view.window().open_file(filepath+":"+str(item[3]),sublime.ENCODED_POSITION)
else:
sublime.status_message("%s not exists"%(filepath))
def is_enabled(self):
sel=self.view.substr(self.view.sel()[0])
if len(sel)==0:
return False
return True
def is_visible(self):
return helper.checkFileExt(self.view.file_name(),"py")
# 重建用户跳转及提示文件
class PythonRebuildUserDefinitionCommand(sublime_plugin.WindowCommand):
def __init__(self,window):
super(PythonRebuildUserDefinitionCommand,self).__init__(window)
self.lastTime=0
def run(self, dirs):
curTime=time.time()
if curTime-self.lastTime<3:
sublime.status_message("Rebuild frequently!")
return
self.lastTime=curTime
global USER_DEFINITION_LIST
USER_DEFINITION_LIST=rebuild.rebuild(dirs[0],TEMP_PATH)
path=os.path.join(TEMP_PATH, "user_definition.json")
data=json.dumps(USER_DEFINITION_LIST)
if not os.path.exists(TEMP_PATH):
os.makedirs(TEMP_PATH)
helper.writeFile(path,data)
sublime.status_message("Rebuild user definition complete!")
def is_enabled(self, dirs):
return len(dirs)==1
def is_visible(self, dirs):
return self.is_enabled(dirs)
# 监听保存后就解析文件
class PythonListener(sublime_plugin.EventListener):
def __init__(self):
self.lastTime=0
def on_post_save(self, view):
filename=view.file_name()
if not filename:
return
if not helper.checkFileExt(filename,"py"):
return
# rebuild user definition
curTime=time.time()
if curTime-self.lastTime<2:
return
self.lastTime=curTime
a=rebuild.rebuildSingle(filename,TEMP_PATH)
arr=a[0]
path=a[1]
# remove prev
global USER_DEFINITION_LIST
for i in range(len(USER_DEFINITION_LIST)-1,0,-1):
item=USER_DEFINITION_LIST[i]
if item[2]==path:
USER_DEFINITION_LIST.remove(item)
USER_DEFINITION_LIST.extend(arr)
path=os.path.join(TEMP_PATH, "user_definition.json")
data=json.dumps(USER_DEFINITION_LIST)
if not os.path.exists(TEMP_PATH):
os.makedirs(TEMP_PATH)
helper.writeFile(path,data)
sublime.status_message("Current file definition rebuild complete!")
# st3
def plugin_loaded():
sublime.set_timeout(init, 200)
# st2
if not helper.isST3():
init()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/lonewolf/pythonDev.git
git@gitee.com:lonewolf/pythonDev.git
lonewolf
pythonDev
pythonDev
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891