我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sublime.version()。
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
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 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)
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 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
def backupMenu(): if not os.path.isdir(dDir): return if not getSetting('auto_backup', True): return bDir = os.path.join(mDir, version, 'backup') if not os.path.isdir(bDir): os.makedirs(bDir) for item in os.listdir(dDir): filename = os.path.join(dDir, item) if os.path.isfile(filename) and item.endswith(mExt[:-5]): target = os.path.join(bDir, item + mExt[-5:]) open(target, 'wb').write(open(filename, 'rb').read())
def restoreMenu(): if not os.path.isdir(dDir): os.makedirs(dDir) for item in os.listdir(dDir): filename = os.path.join(dDir, item) if os.path.isfile(filename) and item.endswith(mExt[:-5]): os.remove(filename) bDir = os.path.join(mDir, version, 'backup') if not os.path.isdir(bDir): return for item in os.listdir(bDir): filename = os.path.join(bDir, item) if os.path.isfile(filename) and item.endswith(mExt): target = os.path.join(dDir, item[:-5]) open(target, 'wb').write(open(filename, 'rb').read())
def init(): if v == '3' and (sublime.installed_packages_path() in pDir): pkgDir = os.path.join(sublime.packages_path(), pName); if not os.path.isdir(pkgDir): pkgFile = os.path.dirname(os.path.abspath(__file__)) unpackSelf(pkgFile, pkgDir) return locale = '' firstRun = False fFile = os.path.join(pDir, '.firstRun') if not os.path.isfile(fFile): firstRun = True backupMenu() open(fFile, 'wt').write('') locale = getSetting('locale', '') eDir = os.path.join(mDir, version, 'en'); if v == '3' and not os.path.isdir(eDir): eFile = sublime.executable_path(); dFile = os.path.join(os.path.dirname(eFile), 'Packages', 'Default.sublime-package'); unpackMenu(dFile, eDir); makeMenu(locale, firstRun) makeCommand(locale, firstRun) setLocale(locale, firstRun) s = sublime.load_settings(sFile) s.add_on_change('locale', updateLocale)
def _get_package_version(): pkg_json = sublime.load_resource("Packages/" + settings.PACKAGE_NAME + "/package.json") return json.loads(pkg_json)["version"]
def __exit__(self, type, value, traceback): view = self.view if sublime.version().startswith('2'): edit = view.begin_edit() self.run(edit) view.end_edit(edit) else: key = str(hash(tuple(self.steps))) sublime.edit_storage[key] = self.run view.run_command('apply_edit', {'key': key})
def write(self, content): with open(self.path(), 'w+', encoding='utf8', newline='') as f: f.write(str(content)) if 3000 <= int(sublime.version()) < 3088: # Fixes as best as possible a new file permissions issue # See https://github.com/titoBouzout/SideBarEnhancements/issues/203 # See https://github.com/SublimeTextIssues/Core/issues/239 oldmask = os.umask(0o000) if oldmask == 0: os.chmod(self.path(), 0o644) os.umask(oldmask)
def _makedirs(self, path): if 3000 <= int(sublime.version()) < 3088: # Fixes as best as possible a new directory permissions issue # See https://github.com/titoBouzout/SideBarEnhancements/issues/203 # See https://github.com/SublimeTextIssues/Core/issues/239 oldmask = os.umask(0o000) if oldmask == 0: os.makedirs(path, 0o755); else: os.makedirs(path); os.umask(oldmask) else: os.makedirs(path)
def has_libclang(): """Ensure libclang tests will run only on platforms that support this. Returns: str: row contents """ # Older version of Sublime Text x64 have ctypes crash bug. if platform.system() == "Windows" and sublime.arch() == "x64" and \ int(sublime.version()) < 3123: return False return True
def __init__(self, theme: str) -> None: self.theme = theme if int(sublime.version()) < 3070: return if Tooltip.loaded is False: self._load_css_themes() self._load_tooltips() Tooltip.loaded = True
def _show_popup(self, view: sublime.View) -> None: """Show message in a popup if sublime text version is >= 3070 """ show_doc = get_settings(view, 'merge_signatures_and_doc', True) content = {'content': self.signature} display_tooltip = 'signature' if show_doc: content = {'signature': self.signature, 'doc': self.doc} display_tooltip = 'signature_doc' css = get_settings(view, 'anaconda_tooltip_theme', 'dark') Tooltip(css).show_tooltip( view, display_tooltip, content, partial(self._show_status, view))
def get_package_and_resource_name(path): """ This method will return the package name and resource name from a path. Arguments: path Path to parse for package and resource name. """ package = None resource = None path = _normalize_to_sublime_path(path) if os.path.isabs(path): packages_path = _normalize_to_sublime_path(sublime.packages_path()) if path.startswith(packages_path): package, resource = _search_for_package_and_resource(path, packages_path) if int(sublime.version()) >= 3006: packages_path = _normalize_to_sublime_path(sublime.installed_packages_path()) if path.startswith(packages_path): package, resource = _search_for_package_and_resource(path, packages_path) packages_path = _normalize_to_sublime_path(os.path.dirname(sublime.executable_path()) + os.sep + "Packages") if path.startswith(packages_path): package, resource = _search_for_package_and_resource(path, packages_path) else: path = re.sub(r"^Packages/", "", path) split = re.split(r"/", path, 1) package = split[0] package = package.replace(".sublime-package", "") resource = split[1] return (package, resource)
def get_packages_list(ignore_packages=True, ignore_patterns=[]): """ Return a list of packages. """ package_set = set() package_set.update(_get_packages_from_directory(sublime.packages_path())) if int(sublime.version()) >= 3006: package_set.update(_get_packages_from_directory(sublime.installed_packages_path(), ".sublime-package")) executable_package_path = os.path.dirname(sublime.executable_path()) + os.sep + "Packages" package_set.update(_get_packages_from_directory(executable_package_path, ".sublime-package")) if ignore_packages: ignored_list = sublime.load_settings( "Preferences.sublime-settings").get("ignored_packages", []) else: ignored_list = [] for package in package_set: for pattern in ignore_patterns: if re.match(pattern, package): ignored_list.append(package) break for ignored in ignored_list: package_set.discard(ignored) return sorted(list(package_set))
def collect(self): self.elements.clear() db0 = DataBlock('Version and architecture') db0.items.append(DataItem('name', 'Sublime Text')) db0.items.append(DataItem('version', sublime.version())) db0.items.append(DataItem('architecture', sublime.arch())) db0.items.append(DataItem('channel', sublime.channel())) db0.items.append(DataItem('platform', sublime.platform())) view = sublime.active_window().active_view() view_settings = view.settings() db1 = DataBlock('View settings') for setting_name in ('syntax', 'tab_size', 'translate_tabs_to_spaces'): db1.items.append(DataItem(setting_name, view_settings.get(setting_name))) db2 = DataBlock('View state') db2.items.append(DataItem('is view dirty', view.is_dirty())) db2.items.append(DataItem('is view readonly', view.is_read_only())) db1.items.append(DataItem('encoding', view.encoding())) db1.items.append(DataItem('em width', view.em_width())) db1.items.append(DataItem('selection count', len(view.sel()))) db1.items.append(DataItem('has non empty selections', view.has_non_empty_selection_region())) self.elements.append(db0) # TODO: Split the rest up into methods. self.collect_package_data() self.elements.append(db1) self.elements.append(db2) self.collect_profiling_data()
def collect_profiling_data(self): if sublime.version() < '3102': return from Default.profile import profile_text block = DataBlock('Profiling data (as reported by Default/profile.py)') block.items.append(PreItem(profile_text().strip())) self.elements.append(block)
def add_regions(self, regions): package_name = (PLUGIN_FOLDER.split(os.path.sep))[-1] if int(sublime.version()) >= 3000: icon = "Packages/" + package_name + "/warning.png" self.view.add_regions("solium_errors", regions, "keyword", icon, sublime.DRAW_EMPTY | sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE | sublime.DRAW_SQUIGGLY_UNDERLINE) else: icon = ".." + os.path.sep + package_name + os.path.sep + "warning" self.view.add_regions("solium_errors", regions, "keyword", icon, sublime.DRAW_EMPTY | sublime.DRAW_OUTLINED)