forked from mattiasnordin/StataEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StataEditorPlugin.py
187 lines (162 loc) · 6.56 KB
/
StataEditorPlugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import sublime, sublime_plugin
import os
import Pywin32.setup
import win32com.client
import win32api
import tempfile
import subprocess
import re
import urllib
from urllib import request
import time
import os
settings_file = "StataEditor.sublime-settings"
# def is_running(process):
# """ Check if process is running """
# wmi = win32com.client.GetObject('winmgmts:')
# for p in wmi.InstancesOf('win32_process'):
# if re.search(process, p.Name):
# return True
# return False
def find_files(file_ext):
""" Create list of all files in project folders with given file extension """
project_folders = []
project_data = sublime.active_window().project_data()
if project_data:
for i in range(0,len(project_data['folders'])):
project_folders.append(project_data['folders'][i]['path'])
else:
project_folders = ['.']
start_time = time.time()
for new_path in project_folders:
for root, dirs, files in os.walk(new_path):
for file in files:
if file.endswith(file_ext):
relDir = os.path.relpath(root, new_path)
relFile = os.path.join(relDir, file)
sublime.file_list.append(relFile.replace('\\', '/'))
diff_time = time.time() - start_time
# With huge folders, the loop can take a long time and freeze ST.
# This condition tries to limit this problem by
# breaking if the loop takes more than 1 second.
# However it can only break between folders, so one huge folder
# could still lead to memory leaks.
if diff_time > 1:
return
def temp_file_exists():
""" Check a given temp file exists """
file_name = 'emergency_close_stata_st.dta'
tmp_dta = os.path.join(tempfile.gettempdir(), file_name)
for file in os.listdir(tempfile.gettempdir()):
if file == file_name:
return True, tmp_dta
return False, tmp_dta
def plugin_loaded():
global settings
settings = sublime.load_settings(settings_file)
def StataAutomate(stata_command):
""" Launch Stata (if needed) and send commands """
# Switch to the proj. dir. Otherwise, we need to create a proj. in ST3
os.chdir(getDirectory().replace('"', ''))
try:
sublime.stata.DoCommandAsync(stata_command)
except:
win32api.WinExec(settings.get("stata_path"))
if settings.get("stata_version") >= 15:
# Extra time is needed for the Dispatch command to hook up to
# the already launched Stata. Change "waiting_time" setting as needed.
time.sleep(settings.get("waiting_time"))
sublime.stata = win32com.client.Dispatch("stata.StataOLEApp")
sublime.stata.DoCommand("cd " + getDirectory())
sublime.stata.DoCommandAsync(stata_command)
if settings.get("file_completions") != False:
sublime.file_list = []
for file_ext in settings.get("file_completions").split(","):
find_files("." + file_ext.strip())
def getDirectory():
var_dict = sublime.active_window().extract_variables()
if settings.get("default_path") == "current_path":
try:
set_dir = "%(file_path)s" % var_dict
set_dir = "\"" + set_dir + "\""
except:
try:
set_dir = "%(project_path)s" % var_dict
set_dir = "\"" + set_dir + "\""
except:
set_dir = ""
elif settings.get("default_path") == "project_path" or settings.get("default_path") == "":
try:
set_dir = "%(project_path)s" % var_dict
set_dir = "\"" + set_dir + "\""
except:
set_dir = ""
else:
set_dir = settings.get("default_path")
set_dir = "\"" + set_dir + "\""
return set_dir
def SelectCode(self,selection):
all_text = ""
len_sels = 0
sels = self.view.sel()
len_sels = 0
for sel in sels:
len_sels = len_sels + len(sel)
if len_sels == 0 and selection == "default":
all_text = self.view.substr(self.view.find('(?s).*',0))
elif len_sels != 0 and selection == "default":
for sel in sels:
self.view.sel().add(self.view.line(sel.begin()))
self.view.sel().add(self.view.line(sel.end()))
for sel in sels:
all_text = all_text + self.view.substr(sel) + "\n"
elif selection == "rest_of_file":
first_sel = sels[0]
self.view.sel().add(self.view.line(first_sel.begin()))
orig_sel_region = sublime.Region(first_sel.begin(),self.view.size())
self.view.sel().add(orig_sel_region)
for sel in sels:
all_text = all_text + self.view.substr(sel) + "\n"
elif selection == "run_above":
first_sel = sels[0]
self.view.sel().add(self.view.line(first_sel.begin()))
orig_sel_region = sublime.Region(0, first_sel.end())
self.view.sel().add(orig_sel_region)
for sel in sels:
all_text = all_text + self.view.substr(sel) + "\n"
elif selection == "line":
for sel in sels:
all_text = all_text + self.view.substr(self.view.line(sel)) + "\n"
elif selection == "selection_only":
for sel in sels:
all_text = all_text + self.view.substr(sel) + "\n"
if all_text[-1] != "\n":
all_text = all_text + "\n"
return all_text
class StataExecuteCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
all_text = SelectCode(self,args["Selection"])
dofile_path = os.path.join(tempfile.gettempdir(), 'st_stata_temp.tmp')
if settings.get("stata_version") <= 13:
this_file = open(dofile_path,'w',encoding=settings.get("character_encoding"))
if settings.get("stata_version") >= 14:
this_file = open(dofile_path,'w',encoding='utf-8')
this_file.write(all_text)
this_file.close()
nr_w_close = 0
StataAutomate(str(args["Mode"]) + ' "' + dofile_path +'"')
class StataLocal(sublime_plugin.TextCommand):
def run(self,edit):
sels = self.view.sel()
for sel in sels:
if len(sel) == 0:
word_sel = self.view.word(sel.a)
else:
word_sel = sel
word_str = self.view.substr(word_sel)
word_str = "`"+word_str+"'"
self.view.replace(edit,word_sel,word_str)
class StataLoad(sublime_plugin.TextCommand):
def run(self,edit):
sel = self.view.substr(self.view.sel()[0])
StataAutomate("use " + sel + ", clear")