Repository navigation
Expand file tree
/
Copy pathTerminal.py
More file actions
194 lines (167 loc) · 7.42 KB
/
Copy pathTerminal.py
File metadata and controls
194 lines (167 loc) · 7.42 KB
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
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 os.name == '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():
package_dir = os.path.join(sublime.packages_path(), installed_dir)
terminal = get_setting('terminal')
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.putenv('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 | 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:
if 'gnome-session' in wm[0] or wm[0] == 'cinnamon-sessio':
default = 'gnome-terminal'
elif wm[0] == 'xfce4-session':
default = 'xfce4-terminal'
elif wm[0] == 'ksmserver':
default = 'konsole'
elif wm[0] == 'lxsession':
default = 'lxterminal'
elif wm[0] == 'mate-panel':
default = 'mate-terminal'
if not default:
default = 'xterm'
TerminalSelector.default = default
return default
class TerminalCommand():
def get_path(self, paths):
if paths:
for path in paths:
if os.path.expanduser(path) in self.window.active_view().file_name():
return path
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_, parameters):
view = self.window.active_view()
replaces = {
'%CWD%': dir_,
'%FILE%': self.window.active_view().file_name(),
'%LINE%': str(view.rowcol(view.sel()[0].begin())[0] + 1)
}
try:
if not dir_:
raise NotFoundError('The file open in the selected view has ' +
'not yet been saved')
for k, v in enumerate(parameters):
for old, new in replaces.items():
v = v.replace(old, new)
parameters[k] = v
args = [TerminalSelector.get()]
args.extend(parameters)
encoding = locale.getpreferredencoding(do_setlocale=True)
dir_ = os.path.expanduser(dir_)
if sys.version_info >= (3,):
cwd = dir_
else:
cwd = dir_.encode(encoding)
subprocess.Popen(args, cwd=cwd)
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):
path = self.get_path(paths)
if not path:
return
if parameters is None:
parameters = get_setting('parameters', [])
if os.path.isfile(path):
path = os.path.dirname(path)
self.run_terminal(path, 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)