def run_shell_command(self, command, working_dir):
if not command:
return False
if BEFORE_CALLBACK:
os.system(BEFORE_CALLBACK)
if AFTER_CALLBACK:
command += " ; " + AFTER_CALLBACK
self.save_test_run(command, working_dir)
if COMMAND_PREFIX:
command = COMMAND_PREFIX + ' ' + command
if int(sublime.version().split('.')[0]) <= 2:
command = [command]
self.view.window().run_command("exec", {
"cmd": command,
"shell": True,
"working_dir": working_dir,
"file_regex": r"([^ ]*\.ex?):?(\d*)",
"encoding": TERMINAL_ENCODING
})
self.display_results()
return True
python类version()的实例源码
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)
def openDiffInTab(viewHandle, edit, oldTextName, newTextName, oldText, newText):
diffs = difflib.unified_diff(oldText.splitlines(), newText.splitlines(), oldTextName, newTextName)
diffText = u"\n".join(line for line in diffs)
if diffText == "":
sublime.status_message("No changes between revisions.")
else:
scratch = viewHandle.window().new_file()
scratch.set_scratch(True)
scratch.set_name("{old} -> {new}".format(old = oldTextName, new = newTextName))
scratch.set_syntax_file("Packages/Diff/Diff.tmLanguage")
if (int(sublime.version()) >= 3000):
scratch.run_command("append", {"characters": diffText})
else:
scratch.insert(edit, 0, diffText)
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_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 show_tooltip(self, view: sublime.View, tooltip: str, content: Dict[str, str], fallback: Callable) -> None: # noqa
"""Generates and display a tooltip or pass execution to fallback
"""
st_ver = int(sublime.version())
if st_ver < 3070:
return fallback()
width = get_settings(view, 'font_size', 8) * 75
kwargs = {'location': -1, 'max_width': width if width < 900 else 900}
if st_ver >= 3071:
kwargs['flags'] = sublime.COOPERATE_WITH_AUTO_COMPLETE
text = self._generate(tooltip, content)
if text is None:
return fallback()
return view.show_popup(text, **kwargs)
def run(self, edit: sublime.Edit) -> None:
if self.documentation is None:
try:
location = self.view.rowcol(self.view.sel()[0].begin())
if self.view.substr(self.view.sel()[0].begin()) in ['(', ')']:
location = (location[0], location[1] - 1)
data = prepare_send_data(location, 'doc', 'jedi')
if int(sublime.version()) >= 3070:
data['html'] = get_settings(
self.view, 'enable_docstrings_tooltip', False)
Worker().execute(
Callback(on_success=self.prepare_data), **data
)
except Exception as error:
print(error)
else:
if (get_settings(self.view, 'enable_docstrings_tooltip', False)
and int(sublime.version()) >= 3070):
self.print_popup(edit)
else:
self.print_doc(edit)
def _complete(self, data: Dict[str, Any]) -> None:
view = active_view()
proposals = data['completions'] if data['success'] else []
if proposals:
if int(sublime.version()) >= 3103 and view.is_auto_complete_visible(): # noqa
view.run_command("hide_auto_complete")
else:
view.run_command("hide_auto_complete")
self.completions = proposals
self.ready_from_defer = True
# if the tab key is used to complete just undo the last insertion
if view.command_history(0)[0] == 'insert_best_completion':
if view.substr(sublime.Region(
view.sel()[0].begin() - 5,
view.sel()[0].end())) == 'self.':
view.run_command('undo')
self._run_auto_complete()
def communicate(self, cmd, code=None):
"""Run an external executable using stdin to pass code and return its output."""
if '__RELATIVE_TO_FOLDER__' in cmd:
relfilename = self.filename
window = self.view.window()
# can't get active folder, it will work only if there is one folder in project
if int(sublime.version()) >= 3080 and len(window.folders()) < 2:
vars = window.extract_variables()
if 'folder' in vars:
relfilename = os.path.relpath(self.filename, vars['folder'])
cmd[cmd.index('__RELATIVE_TO_FOLDER__')] = relfilename
elif not code:
cmd.append(self.filename)
return super().communicate(cmd, code)
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 file_directory():
"""Returns the given file directory
"""
if int(sublime.version()) >= 3080:
# extract_variables was added to ST3 rev 3080
return sublime.active_window().extract_variables().get('file_path')
folders = sublime.active_window().folders()
if len(folders) > 0:
return folders[0]
return tempfile.gettempdir()
# reuse anaconda helper functions
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)
CrossPlatformCodecs.py 文件源码
项目:sublime-commandbox
作者: Ortus-Solutions
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def encode_process_command(self, command):
is_sublime_2_and_in_windows = sublime.platform() == "windows" and int(sublime.version()) < 3000
return command.encode(sys.getfilesystemencoding()) if is_sublime_2_and_in_windows else command
def __init__(self):
self._project_data = sublime.active_window().project_data().get('Commandbox', {}) if int(sublime.version()) >= 3000 else {}
def format_version(module, attr, call=False):
try:
if call:
version = getattr(module, attr)()
else:
version = getattr(module, attr)
except Exception as e:
print(e)
version = 'Version could not be acquired!'
if not isinstance(version, str):
version = list2string(version)
return version
def parse_global(self):
"""Parse global settings."""
color_settings = {}
for item in self.csm.plist_file["settings"]:
if item.get('scope', None) is None and item.get('name', None) is None:
color_settings = item["settings"]
break
# Get general theme colors from color scheme file
self.bground = self.strip_color(color_settings.get("background", '#FFFFFF'), simple_strip=True)
rgba = RGBA(self.bground)
self.lums = rgba.get_luminance()
is_dark = self.lums <= LUM_MIDPOINT
settings = sublime.load_settings("Preferences.sublime-settings")
self.variables = {
"is_dark": is_dark,
"is_light": not is_dark,
"sublime_version": int(sublime.version()),
"mdpopups_version": ver.version(),
"color_scheme": self.scheme_file,
"use_pygments": not settings.get('mdpopups.use_sublime_highlighter', False),
"default_formatting": settings.get('mdpopups.default_formatting', True)
}
self.html_border = rgba.get_rgb()
self.fground = self.strip_color(color_settings.get("foreground", '#000000'))
# Intialize colors with the global foreground, background, and fake html_border
self.colors = OrderedDict()
self.colors['.foreground'] = OrderedDict([('color', 'color: %s; ' % self.fground)])
self.colors['.background'] = OrderedDict([('background-color', 'background-color: %s; ' % self.bground)])
def gen_css(self):
"""Generate the CSS and the associated template environment."""
self.colors = OrderedDict()
self.parse_global()
self.parse_settings()
# Assemble the CSS text
text = []
css_entry = '%s { %s}' if int(sublime.version()) < 3119 else '.mdpopups %s { %s}'
for k, v in self.colors.items():
text.append(css_entry % (k, ''.join(v.values())))
self.text = '\n'.join(text)
# Create Jinja template
self.env = jinja2.Environment()
self.env.filters['css'] = self.retrieve_selector
self.env.filters['pygments'] = self.pygments
self.env.filters['foreground'] = self.to_fg
self.env.filters['background'] = self.to_bg
self.env.filters['brightness'] = self.brightness
self.env.filters['colorize'] = self.colorize
self.env.filters['hue'] = self.hue
self.env.filters['invert'] = self.invert
self.env.filters['saturation'] = self.saturation
self.env.filters['grayscale'] = self.grayscale
self.env.filters['sepia'] = self.sepia
self.env.filters['fade'] = self.fade
self.env.filters['getcss'] = self.read_css
self.env.filters['relativesize'] = self.relativesize
def version():
"""Get the current version."""
return ver.version()
def processRecentUpgrade():
if (VERSION in UPGRADE_KILL_FILES):
print("Performing kill for version %1.1f" % (VERSION))
for killed in UPGRADE_KILL_FILES[VERSION]:
killPath = os.path.join(sublime.packages_path(), "PapyrusF4", killed)
if os.path.exists(killPath):
if killed[-1] == "/":
shutil.rmtree(killPath)
else:
os.remove(killPath)
def run(self, edit):
self.fileName = self.view.file_name()
self.prefs = getPrefs(os.path.dirname(self.fileName))
refresh = False
# does cache file exist?
fname = ensureCacheDirectory()
fname = os.path.join(fname, "WikiPagesCache.txt")
if not os.path.exists(fname):
refresh = True
else:
touched = os.path.getmtime(fname)
three_days = time.time() - 60*60*24*3 # three days ago in seconds
if touched < three_days:
refresh = True
if (refresh):
if (int(sublime.version()) >= 3000):
outText = "\n".join(list(self.getPapyrusPages())).strip()
else:
outText = "\n".join(list(self.getPapyrusPages())).encode("utf-8").strip()
with open(fname, "w") as fileHandle:
fileHandle.write(str(outText))
with open(fname, "r") as f:
self.papyrusPages = f.readlines()
self.processingSelections = self.view.sel()
self.pagesToOpen = []
self.processTopSelection()
def __init__(self):
self.settings = None
self.sublime_version = int(float(sublime.version()))
self.DXWindows = {}
def parse_global(self):
"""Parse global settings."""
color_settings = {}
for item in self.csm.plist_file["settings"]:
if item.get('scope', None) is None and item.get('name', None) is None:
color_settings = item["settings"]
break
# Get general theme colors from color scheme file
self.bground = self.process_color(color_settings.get("background", '#FFFFFF'), simple_strip=True)
rgba = RGBA(self.bground)
self.lums = rgba.get_luminance()
is_dark = self.lums <= LUM_MIDPOINT
settings = sublime.load_settings("Preferences.sublime-settings")
self.variables = {
"is_dark": is_dark,
"is_light": not is_dark,
"sublime_version": int(sublime.version()),
"mdpopups_version": ver.version(),
"color_scheme": self.scheme_file,
"use_pygments": not settings.get('mdpopups.use_sublime_highlighter', False),
"default_formatting": settings.get('mdpopups.default_formatting', True),
"default_style": settings.get('mdpopups.default_style', True)
}
self.html_border = rgba.get_rgb()
self.fground = self.process_color(color_settings.get("foreground", '#000000'))
# Intialize colors with the global foreground, background, and fake html_border
self.colors = OrderedDict()
self.colors['.foreground'] = OrderedDict([('color', 'color: %s; ' % self.fground)])
self.colors['.background'] = OrderedDict([('background-color', 'background-color: %s; ' % self.bground)])
def gen_css(self):
"""Generate the CSS and the associated template environment."""
self.colors = OrderedDict()
self.parse_global()
self.parse_settings()
# Assemble the CSS text
text = []
css_entry = '%s { %s}' if int(sublime.version()) < 3119 else '.mdpopups %s { %s}'
for k, v in self.colors.items():
text.append(css_entry % (k, ''.join(v.values())))
self.text = '\n'.join(text)
# Create Jinja template
self.env = jinja2.Environment()
self.env.filters['css'] = self.retrieve_selector
self.env.filters['pygments'] = self.pygments
self.env.filters['foreground'] = self.to_fg
self.env.filters['background'] = self.to_bg
self.env.filters['brightness'] = self.brightness
self.env.filters['colorize'] = self.colorize
self.env.filters['hue'] = self.hue
self.env.filters['invert'] = self.invert
self.env.filters['saturation'] = self.saturation
self.env.filters['grayscale'] = self.grayscale
self.env.filters['sepia'] = self.sepia
self.env.filters['fade'] = self.fade
self.env.filters['getcss'] = self.read_css
self.env.filters['relativesize'] = self.relativesize
def version():
"""Get the current version."""
return ver.version()
def subl_import(pkg, obj=''):
repo = os.path.realpath(__file__).split(os.sep)[-3]
o = [obj] if obj != '' else []
p = pkg if version() < '3000' else repo+'.'+pkg
imp = __import__(p, None, None, o)
return getattr(imp, obj, imp)
def set_xml(this):
if sublime.version() >= "3103":
this.view.set_syntax_file('Packages/XML/XML.sublime-syntax')
else:
this.view.set_syntax_file('Packages/XML/XML.tmLanguage')
# this.rename_file(this)
def set_json(this):
if sublime.version() >= "3103":
this.view.set_syntax_file('Packages/JavaScript/JSON.sublime-syntax')
else:
this.view.set_syntax_file('Packages/JavaScript/JSON.tmLanguage')
# this.rename_file(this)
def isST3():
return int(sublime.version()) > 3000
def setLocale(locale, force = False):
if not locale:
return
if (not force) and locale == getSetting('locale'):
return
link = getLink(locale)
if link:
locale = link
m = {}
d = os.path.join(mDir, v, locale)
m.update(findMenu(d))
sDir = ''
d = os.path.join(mDir, version)
ld = os.path.join(d, locale)
if (not os.path.isdir(ld)) and getSetting('findSimilarVer', True):
sDir = findSimilarVer()
if not sDir:
return
d = os.path.join(mDir, sDir)
d = os.path.join(d, locale)
if not os.path.isdir(d):
return
m.update(findMenu(d))
d = os.path.join(d, p)
m.update(findMenu(d))
d = os.path.join(d, sublime.arch())
m.update(findMenu(d))
updateMenu(m)
if getSetting('updateTopMenu', True):
updateTopMenu()
sublime.status_message('Locale ' + locale + ' has loaded.')
def findSimilarVer():
sVer = ''
for item in os.listdir(mDir):
subDir = os.path.join(mDir, item)
if os.path.isdir(subDir) and item.isdigit() and item < version:
sVer = item
return sVer