def run(self):
info = {}
info['platform'] = sublime.platform()
info['version'] = sublime.version()
info['file_icons_version'] = __version__
info['pc_install'] = is_installed_by_package_control()
info['current_theme'] = get_current_theme()
info['installed_themes'] = get_installed_themes()
msg = textwrap.dedent(
'''\
- File Icons: %(file_icons_version)s
- Sublime Text: %(version)s
- Platform: %(platform)s
- Package Control: %(pc_install)s
- Current Theme: %(current_theme)s
- Installed Themes: %(installed_themes)s
''' % info
)
sublime.message_dialog(
msg + '\nInfo has been copied to the clipboard.'
)
sublime.set_clipboard(msg)
python类platform()的实例源码
def find_ancestor_cmd_path(self, cmd, cwd):
"""Recursively check for command binary in ancestors' node_modules/.bin directories."""
node_modules_bin = path.normpath(path.join(cwd, 'node_modules/.bin/'))
binary = path.join(node_modules_bin, cmd)
if sublime.platform() == 'windows' and path.splitext(binary)[1] != '.cmd':
binary += '.cmd'
if binary and access(binary, X_OK):
return binary
parent = path.normpath(path.join(cwd, '../'))
if parent == '/' or parent == cwd:
return None
return self.find_ancestor_cmd_path(cmd, parent)
def packages_relative_path(path, prefix_packages=True):
"""
Return a Packages-relative version of path with '/' as the path separator.
Sublime Text wants Packages-relative paths used in settings and in the plugin API
to use '/' as the path separator on all platforms. This method converts platform
path separators to '/'. If insert_packages = True, 'Packages' is prefixed to the
converted path.
"""
components = get_path_components(path)
if prefix_packages and components and components[0] != 'Packages':
components.insert(0, 'Packages')
return '/'.join(components)
def find_python_script(python_path, script):
"""Return the path to the given script, or None if not found."""
if sublime.platform() in ('osx', 'linux'):
pyenv = which('pyenv')
if pyenv:
out = run_shell_cmd((os.environ['SHELL'], '-l', '-c',
'echo ""; {} which {}'.format(pyenv, script))).strip().decode().split('\n')[-1]
if os.path.isfile(out):
return out
return which(script)
else:
# On Windows, scripts may be .exe files or .py files in <python directory>/Scripts
scripts_path = os.path.join(os.path.dirname(python_path), 'Scripts')
script_path = os.path.join(scripts_path, script + '.exe')
if os.path.exists(script_path):
return script_path
script_path = os.path.join(scripts_path, script + '-script.py')
if os.path.exists(script_path):
return script_path
return None
def get_font_scale(self):
"""Get font scale."""
scale = 1.0
try:
pref_scale = float(sublime.load_settings('Preferences.sublime-settings').get('mdpopups.font_scale', 0.0))
except Exception:
pref_scale = 0.0
if sublime.platform() == 'windows' and pref_scale <= 0.0:
try:
import ctypes
logpixelsy = 90
dc = ctypes.windll.user32.GetDC(0)
height = ctypes.windll.gdi32.GetDeviceCaps(dc, logpixelsy)
scale = float(height) / 96.0
ctypes.windll.user32.ReleaseDC(0, dc)
except Exception:
pass
elif pref_scale > 0.0:
scale = pref_scale
return scale
def run(self):
if sublime.platform() == "linux":
preset_path = "/usr/share/%s/" % APP_NAME.lower()
elif sublime.platform() == "windows":
preset_path = "C:/%s/" % APP_NAME.lower()
elif platform.system() == "Darwin":
preset_path = os.path.join(os.path.expanduser("~"),
"Applications",
"%s.app" % APP_NAME,
"Contents",
"Resources",
APP_NAME)
else:
preset_path = ""
self.window.show_input_panel("Set Kodi folder",
preset_path,
self.set_kodi_folder,
None,
None)
def run(self, edit, encoding, file_name, need_codecs):
self.view.set_name('ConvertToUTF8 Instructions')
self.view.set_scratch(True)
self.view.settings().set("word_wrap", True)
msg = 'File: {0}\nEncoding: {1}\nError: '.format(file_name, encoding)
if need_codecs:
msg = msg + 'Codecs missing\n\n'
branch = self.get_branch(sublime.platform(), sublime.arch())
if branch:
ver = '33' if ST3 else '26'
msg = msg + 'Please install Codecs{0} plugin (https://github.com/seanliang/Codecs{0}/tree/{1}).\n'.format(ver, branch)
else:
import platform
msg = msg + 'Please send the following information to sunlxy (at) yahoo.com:\n====== Debug Information ======\nVersion: {0}-{1}\nPlatform: {2}\nPath: {3}\nEncoding: {4}\n'.format(
sublime.version(), sublime.arch(), platform.platform(), sys.path, encoding
)
else:
msg = msg + 'Unsupported encoding, see http://docs.python.org/library/codecs.html#standard-encodings\n\nPlease try other tools such as iconv.\n'
self.view.insert(edit, 0, msg)
self.view.set_read_only(True)
self.view.window().focus_view(self.view)
def get_font_scale(self):
"""Get font scale."""
scale = 1.0
try:
pref_scale = float(sublime.load_settings('Preferences.sublime-settings').get('mdpopups.font_scale', 0.0))
except Exception:
pref_scale = 0.0
if sublime.platform() == 'windows' and pref_scale <= 0.0:
try:
import ctypes
logpixelsy = 90
dc = ctypes.windll.user32.GetDC(0)
height = ctypes.windll.gdi32.GetDeviceCaps(dc, logpixelsy)
scale = float(height) / 96.0
ctypes.windll.user32.ReleaseDC(0, dc)
except Exception:
pass
elif pref_scale > 0.0:
scale = pref_scale
return scale
def run(self, edit):
for region in self.view.sel():
line = self.view.line(region)
cont = self.view.substr(line)
if (len(cont) < 2):
pass
else:
lang = " in " + self.get_syntax()
cont = cont.strip()
cont = cont + lang
p = subprocess.Popen("howdoi " + cont,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
output, errors = p.communicate()
# Decode binary data for python 3
output = output.decode('utf-8')
# Remove CR for windows.
if sublime.platform() == 'windows':
output = output.replace('\r', '')
self.view.replace(edit, line, output)
def is_hidden(self, filename, path, goto=''):
if not (path or goto): # special case for ThisPC
return False
tests = self.view.settings().get('outline_hidden_files_patterns', ['.*'])
if isinstance(tests, str):
tests = [tests]
if any(fnmatch.fnmatch(filename, pattern) for pattern in tests):
return True
if sublime.platform() != 'windows':
return False
# check for attribute on windows:
try:
attrs = ctypes.windll.kernel32.GetFileAttributesW(join(path, goto, filename))
assert attrs != -1
result = bool(attrs & 2)
except (AttributeError, AssertionError):
result = False
return result
def run(self, paths = [], application = "", extensions = "", args=[]):
application_dir, application_name = os.path.split(application)
if extensions == '*':
extensions = '.*'
if extensions == '':
items = SideBarSelection(paths).getSelectedItems()
else:
items = SideBarSelection(paths).getSelectedFilesWithExtension(extensions)
import subprocess
try:
for item in items:
if sublime.platform() == 'osx':
subprocess.Popen(['open', '-a', application] + args + [item.name()], cwd=item.dirname())
elif sublime.platform() == 'windows':
subprocess.Popen([application_name] + args + [escapeCMDWindows(item.path())], cwd=expandVars(application_dir), shell=True)
else:
subprocess.Popen([application_name] + args + [escapeCMDWindows(item.name())], cwd=item.dirname())
except:
sublime.error_message('Unable to "Open With..", probably incorrect path to application.')
def confirm(self, paths, display_paths):
import functools
window = sublime.active_window()
window.show_input_panel("BUG!", '', '', None, None)
window.run_command('hide_panel');
yes = []
yes.append('Yes, delete the selected items.');
for item in display_paths:
yes.append(item);
no = []
no.append('No');
no.append('Cancel the operation.');
while len(no) != len(yes):
no.append('');
if sublime.platform() == 'osx':
sublime.set_timeout(lambda:window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths)), 200);
else:
window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths))
def confirm(self, paths, display_paths):
import functools
window = sublime.active_window()
window.show_input_panel("BUG!", '', '', None, None)
window.run_command('hide_panel');
yes = []
yes.append('Yes, empty the selected items.');
for item in display_paths:
yes.append(item);
no = []
no.append('No');
no.append('Cancel the operation.');
while len(no) != len(yes):
no.append('');
if sublime.platform() == 'osx':
sublime.set_timeout(lambda:window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths)), 200);
else:
window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths))
def run(self, paths = []):
import subprocess
items = []
executable_path = sublime.executable_path()
if sublime.platform() == 'osx':
app_path = executable_path[:executable_path.rfind(".app/")+5]
executable_path = app_path+"Contents/SharedSupport/bin/subl"
items.append(executable_path)
for item in SideBarSelection(paths).getSelectedItems():
items.append(item.forCwdSystemPath())
items.append(item.path())
subprocess.Popen(items, cwd=items[1])
def get_output(cmd):
if int(sublime.version()) < 3000:
if sublime.platform() != "windows":
# Handle Linux and OS X in Python 2.
run = '"' + '" "'.join(cmd) + '"'
return commands.getoutput(run)
else:
# Handle Windows in Python 2.
# Prevent console window from showing.
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.Popen(cmd, \
stdout=subprocess.PIPE, \
startupinfo=startupinfo).communicate()[0]
else:
# Handle all OS in Python 3.
run = '"' + '" "'.join(cmd) + '"'
return subprocess.check_output(run, stderr=subprocess.STDOUT, shell=True, env=os.environ)
def _status(self, timeout=0.05):
"""Check the socket status, returns True if it is operable
"""
check = 'that you can connect to your localhost'
addr = '("localhost", {})'.format(self.interpreter.port)
if sublime.platform() != 'windows':
check = (
'that the Unix Domain Socket file {} exists and that you can '
'connect to it'
).format(self.interpreter.host)
addr = self.interpreter.host
self.tip = (
'check that there is Python process executing the anaconda '
'jsonserver.py script running in your system. If there is, check '
'{} writing the following script in your Sublime Text 3 console:'
'\n\nimport socket; socket.socket(socket.AF_INET, '
'socket.SOCK_STREAM).connect({})\n\nIf anaconda works just fine '
'after you received this error and the command above worked you '
'can make anaconda to do not show you this error anymore setting '
'the \'swallow_startup_errors\' to \'true\' in your '
'configuration file.'.format(check, addr)
)
return super(LocalWorker, self)._status(timeout)
def find_ancestor_cmd_path(self, cmd, cwd):
"""Recursively check for command binary in ancestors' node_modules/.bin directories."""
node_modules_bin = path.normpath(path.join(cwd, 'node_modules/.bin/'))
binary = path.join(node_modules_bin, cmd)
if sublime.platform() == 'windows' and path.splitext(binary)[1] != '.cmd':
binary += '.cmd'
if binary and access(binary, X_OK):
return binary
parent = path.normpath(path.join(cwd, '../'))
if parent == '/' or parent == cwd:
return None
return self.find_ancestor_cmd_path(cmd, parent)
def packages_relative_path(path, prefix_packages=True):
"""
Return a Packages-relative version of path with '/' as the path separator.
Sublime Text wants Packages-relative paths used in settings and in the plugin API
to use '/' as the path separator on all platforms. This method converts platform
path separators to '/'. If insert_packages = True, 'Packages' is prefixed to the
converted path.
"""
components = get_path_components(path)
if prefix_packages and components and components[0] != 'Packages':
components.insert(0, 'Packages')
return '/'.join(components)
def find_python_script(python_path, script):
"""Return the path to the given script, or None if not found."""
if sublime.platform() in ('osx', 'linux'):
pyenv = which('pyenv')
if pyenv:
out = run_shell_cmd((os.environ['SHELL'], '-l', '-c',
'echo ""; {} which {}'.format(pyenv, script))).strip().decode().split('\n')[-1]
if os.path.isfile(out):
return out
return which(script)
else:
# On Windows, scripts may be .exe files or .py files in <python directory>/Scripts
scripts_path = os.path.join(os.path.dirname(python_path), 'Scripts')
script_path = os.path.join(scripts_path, script + '.exe')
if os.path.exists(script_path):
return script_path
script_path = os.path.join(scripts_path, script + '-script.py')
if os.path.exists(script_path):
return script_path
return None
def find_executable(executable):
"""
Return the path to the given executable, or None if not found.
create_environment is used to augment PATH before searching
for the executable.
"""
env = create_environment()
for base in env.get('PATH', '').split(os.pathsep):
path = os.path.join(os.path.expanduser(base), executable)
# On Windows, if path does not have an extension, try .exe, .cmd, .bat
if sublime.platform() == 'windows' and not os.path.splitext(path)[1]:
for extension in ('.exe', '.cmd', '.bat'):
path_ext = path + extension
if can_exec(path_ext):
return path_ext
elif can_exec(path):
return path
return None
def get_font_scale(self):
"""Get font scale."""
scale = 1.0
try:
pref_scale = float(sublime.load_settings('Preferences.sublime-settings').get('mdpopups.font_scale', 0.0))
except Exception:
pref_scale = 0.0
if sublime.platform() == 'windows' and pref_scale <= 0.0:
try:
import ctypes
logpixelsy = 90
dc = ctypes.windll.user32.GetDC(0)
height = ctypes.windll.gdi32.GetDeviceCaps(dc, logpixelsy)
scale = float(height) / 96.0
ctypes.windll.user32.ReleaseDC(0, dc)
except Exception:
pass
elif pref_scale > 0.0:
scale = pref_scale
return scale
def _on_done_select_generator(cls, index):
if index == -1:
cls._is_selecting = False
return
cls.generator = cls.items[index][0]
platform_support = cls.items[index][1]
toolset_support = cls.items[index][2]
cls.platform_support = True if "True" in platform_support else False
cls.toolset_support = True if "True" in toolset_support else False
print("CMakeBuilder: Selected generator is", cls.generator)
if cls.platform_support:
text = "Platform for {} (Press Enter for default): ".format(
cls.generator)
print("CMakeBuilder: Presenting input panel for platform.")
cls.window.show_input_panel(text, "",
cls._on_done_select_platform,
None, None)
elif cls.toolset_support:
cls._select_toolset()
else:
cls._run_configure_with_new_settings()
def get_output(cmd):
if int(sublime.version()) < 3000:
if sublime.platform() != "windows":
# Handle Linux and OS X in Python 2.
run = '"' + '" "'.join(cmd) + '"'
return commands.getoutput(run)
else:
# Handle Windows in Python 2.
# Prevent console window from showing.
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.Popen(cmd, \
stdout=subprocess.PIPE, \
startupinfo=startupinfo).communicate()[0]
else:
# Handle all OS in Python 3.
run = '"' + '" "'.join(cmd) + '"'
return subprocess.check_output(run, stderr=subprocess.STDOUT, shell=True, env=os.environ)
def get_output(cmd):
if int(sublime.version()) < 3000:
if sublime.platform() != "windows":
# Handle Linux and OS X in Python 2.
run = '"' + '" "'.join(cmd) + '"'
return commands.getoutput(run)
else:
# Handle Windows in Python 2.
# Prevent console window from showing.
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.Popen(cmd, \
stdout=subprocess.PIPE, \
startupinfo=startupinfo).communicate()[0]
else:
# Handle all OS in Python 3.
run = '"' + '" "'.join(cmd) + '"'
try:
return subprocess.check_output(run, stderr=subprocess.STDOUT, shell=True, env=os.environ)
except Exception as exception:
print(exception.output)
def run(self, edit):
def done(path):
settings = sublime.load_settings("PICO-8.sublime-settings")
settings.set("pico-8_path", path)
sublime.save_settings("PICO-8.sublime-settings")
return
platform = sublime.platform()
if platform == "linux":
self.view.window().show_input_panel("PICO-8 Path", "/path/to/pico8", done, None, None)
elif platform == "osx":
self.view.window().show_input_panel("PICO-8 Path", "/path/to/PICO-8.app/Contents/MacOS/pico8", done, None, None)
elif platform == "windows":
self.view.window().show_input_panel("PICO-8 Path", "C:\\Program Files (x86)\\PICO-8\\pico8.exe", done, None, None)
else:
sublime.error_message("Error: could not resolve platform\n\n[\"linux\", \"osx\", \"windows\"]")
return
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
if platform() == 'linux':
term = self.view.settings().get('VintageousEx_linux_terminal')
term = term or os.environ.get('COLORTERM') or os.environ.get("TERM")
if not term:
nvim.status_message('not terminal name found')
return
try:
self.open_shell([term, '-e', 'bash']).wait()
except Exception as e:
nvim.console_message(e)
nvim.status_message('error while executing command through shell')
return
elif platform() == 'osx':
term = self.view.settings().get('VintageousEx_osx_terminal')
term = term or os.environ.get('COLORTERM') or os.environ.get("TERM")
if not term:
nvim.status_message('not terminal name found')
return
try:
self.open_shell([term, '-e', 'bash']).wait()
except Exception as e:
nvim.console_message(e)
nvim.status_message('error while executing command through shell')
return
elif platform() == 'windows':
self.open_shell(['cmd.exe', '/k']).wait()
else:
# XXX OSX (make check explicit)
nvim.not_implemented_message('not implemented')
# https://vimhelp.appspot.com/insert.txt.html#:r
def get_node_path():
platform = sublime.platform()
node = PluginUtils.get_pref("node_path").get(platform)
print("Using node.js path on '" + platform + "': " + node)
return node
# Convert path that possibly contains a user tilde and/or is a relative path into an absolute path.
def get_local_eslint(dirname):
pkg = PluginUtils.findup('node_modules/eslint', dirname)
if pkg == None:
return None
else:
path = PluginUtils.get_pref("local_eslint_path").get(sublime.platform())
d = os.path.dirname(os.path.dirname(pkg))
esl = os.path.join(d, path)
if os.path.isfile(esl):
return esl
else:
return None
def get_eslint_path(dirname):
platform = sublime.platform()
eslint = PluginUtils.get_local_eslint(dirname)
# if local eslint not available, then using the settings config
if eslint == None:
eslint = PluginUtils.get_pref("eslint_path").get(platform)
print("Using eslint path on '" + platform + "': " + eslint)
return eslint
def run(self,
cmd="/bin/bash -l",
title="Terminal",
cwd=None,
syntax=None,
keep_open=False):
"""
Open a new terminal view
Args:
cmd (str, optional): Shell to execute. Defaults to 'bash -l.
title (str, optional): Terminal view title. Defaults to 'Terminal'.
cwd (str, optional): The working dir to start out with. Defaults to
either the currently open file, the currently
open folder, $HOME, or "/", in that order of
precedence. You may pass arbitrary snippet-like
variables.
syntax (str, optional): Syntax file to use in the view.
keep_open (bool, optional): Keep view open after cmd exits.
"""
if sublime.platform() not in ("linux", "osx"):
sublime.error_message("TerminalView: Unsupported OS")
return
st_vars = self.window.extract_variables()
if not cwd:
cwd = "${file_path:${folder}}"
cwd = sublime.expand_variables(cwd, st_vars)
if not cwd:
cwd = os.environ.get("HOME", None)
if not cwd:
# Last resort
cwd = "/"
args = {"cmd": cmd, "title": title, "cwd": cwd, "syntax": syntax, "keep_open": keep_open}
self.window.new_file().run_command("terminal_view_activate", args=args)