-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathTerminal.py
213 lines (181 loc) · 8.33 KB
/
Terminal.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import sublime
import sublime_plugin
import os
import sys
import subprocess
import locale
if os.name == 'nt':
try:
import _winreg
except (ImportError):
import winreg as _winreg
from ctypes import windll, create_unicode_buffer
class NotFoundError(Exception):
pass
if sys.version_info >= (3,):
installed_dir, _ = __name__.split('.')
else:
installed_dir = os.path.basename(os.getcwd())
def get_setting(key, default=None):
settings = sublime.load_settings('Terminal.sublime-settings')
os_specific_settings = {}
if os.name == 'nt':
os_specific_settings = sublime.load_settings('Terminal (Windows).sublime-settings')
elif sys.platform == 'darwin':
os_specific_settings = sublime.load_settings('Terminal (OSX).sublime-settings')
else:
os_specific_settings = sublime.load_settings('Terminal (Linux).sublime-settings')
return os_specific_settings.get(key, settings.get(key, default))
class TerminalSelector():
default = None
@staticmethod
def get(terminal_key):
package_dir = os.path.join(sublime.packages_path(), installed_dir)
terminal = get_setting(terminal_key)
if terminal:
dir, executable = os.path.split(terminal)
if not dir:
joined_terminal = os.path.join(package_dir, executable)
if os.path.exists(joined_terminal):
terminal = joined_terminal
if not os.access(terminal, os.X_OK):
os.chmod(terminal, 0o755)
return terminal
if TerminalSelector.default:
return TerminalSelector.default
default = None
if os.name == 'nt':
if os.path.exists(os.environ['SYSTEMROOT'] +
'\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'):
# This mimics the default powershell colors since calling
# subprocess.POpen() ends up acting like launching powershell
# from cmd.exe. Normally the size and color are inherited
# from cmd.exe, but this creates a custom mapping, and then
# the LaunchPowerShell.bat file adjusts some other settings.
key_string = 'Console\\%SystemRoot%_system32_' + \
'WindowsPowerShell_v1.0_powershell.exe'
try:
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
key_string)
except (WindowsError):
key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,
key_string)
_winreg.SetValueEx(key, 'ColorTable05', 0,
_winreg.REG_DWORD, 5645313)
_winreg.SetValueEx(key, 'ColorTable06', 0,
_winreg.REG_DWORD, 15789550)
default = os.path.join(package_dir, 'PS.bat')
sublime_terminal_path = os.path.join(sublime.packages_path(), installed_dir)
# This should turn the path into an 8.3-style path, getting around unicode
# issues and spaces
buf = create_unicode_buffer(512)
if windll.kernel32.GetShortPathNameW(sublime_terminal_path, buf, len(buf)):
sublime_terminal_path = buf.value
os.environ['sublime_terminal_path'] = sublime_terminal_path.replace(' ', '` ')
else :
default = os.environ['SYSTEMROOT'] + '\\System32\\cmd.exe'
elif sys.platform == 'darwin':
default = os.path.join(package_dir, 'Terminal.sh')
if not os.access(default, os.X_OK):
os.chmod(default, 0o755)
else:
ps = 'ps -eo comm,args | grep -E "^(gnome-session|ksmserver|' + \
'xfce4-session|lxsession|mate-panel|cinnamon-sessio)" | grep -v grep'
wm = [x.replace("\n", '') for x in os.popen(ps)]
if wm:
# elementary OS: `/usr/lib/gnome-session/gnome-session-binary --session=pantheon`
# Gnome: `gnome-session` or `gnome-session-binary`
# Linux Mint Cinnamon: `cinnamon-session --session cinnamon`
if wm[0].startswith('gnome-session') or wm[0].startswith('cinnamon-sessio'):
if 'pantheon' in wm[0]:
default = 'pantheon-terminal'
else:
default = 'gnome-terminal'
elif wm[0].startswith('xfce4-session'):
default = 'xfce4-terminal'
elif wm[0].startswith('ksmserver'):
default = 'konsole'
elif wm[0].startswith('lxsession'):
default = 'lxterminal'
elif wm[0].startswith('mate-panel'):
default = 'mate-terminal'
if not default:
default = 'xterm'
TerminalSelector.default = default
return default
class TerminalCommand():
def get_path(self, paths):
if paths:
return paths[0]
# DEV: On ST3, there is always an active view.
# Be sure to check that it's a file with a path (not temporary view)
elif self.window.active_view() and self.window.active_view().file_name():
return self.window.active_view().file_name()
elif self.window.folders():
return self.window.folders()[0]
else:
sublime.error_message('Terminal: No place to open terminal to')
return False
def run_terminal(self, dir_, terminal, parameters):
try:
if not dir_:
raise NotFoundError('The file open in the selected view has ' +
'not yet been saved')
for k, v in enumerate(parameters):
parameters[k] = v.replace('%CWD%', dir_)
args = [TerminalSelector.get(terminal)]
args.extend(parameters)
encoding = locale.getpreferredencoding(do_setlocale=True)
if sys.version_info >= (3,):
cwd = dir_
else:
cwd = dir_.encode(encoding)
# Copy over environment settings onto parent environment
env_setting = get_setting('env', {})
env = os.environ.copy()
for k in env_setting:
if env_setting[k] is None:
env.pop(k, None)
else:
env[k] = env_setting[k]
# Normalize environment settings for ST2
# https://github.com/wbond/sublime_terminal/issues/154
# http://stackoverflow.com/a/4987414
for k in env:
if not isinstance(env[k], str):
if isinstance(env[k], unicode):
env[k] = env[k].encode('utf8')
else:
print('Unsupported environment variable type. Expected "str" or "unicode"', env[k])
# Run our process
subprocess.Popen(args, cwd=cwd, env=env)
except (OSError) as exception:
print(str(exception))
sublime.error_message('Terminal: The terminal ' +
TerminalSelector.get() + ' was not found')
except (Exception) as exception:
sublime.error_message('Terminal: ' + str(exception))
class OpenTerminalCommand(sublime_plugin.WindowCommand, TerminalCommand):
def run(self, paths=[], parameters=None, terminal=None):
path = self.get_path(paths)
if not path:
return
if terminal is None:
terminal = 'terminal'
if parameters is None:
parameters = get_setting('parameters', [])
if os.path.isfile(path):
path = os.path.dirname(path)
self.run_terminal(path, terminal, parameters)
class OpenTerminalProjectFolderCommand(sublime_plugin.WindowCommand,
TerminalCommand):
def run(self, paths=[], parameters=None):
path = self.get_path(paths)
if not path:
return
# DEV: We require separator to be appended since `/hello` and `/hello-world`
# would both match a file in `/hello` without it
# For more info, see https://github.com/wbond/sublime_terminal/issues/86
folders = [x for x in self.window.folders() if path.find(x + os.sep) == 0][0:1]
command = OpenTerminalCommand(self.window)
command.run(folders, parameters=parameters)