Python sublime.platform() Examples
The following are 30
code examples of sublime.platform().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sublime
, or try the search function
.
Example #1
Source File: standard-format.py From sublime-standard-format with MIT License | 10 votes |
def command_version(command): """ Uses subprocess to format a given string. """ startupinfo = None if platform == "windows": # Prevent cmd.exe window from popping up startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= ( subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW ) startupinfo.wShowWindow = subprocess.SW_HIDE std = subprocess.Popen( [command, "--version"], env=calculate_env(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo ) out, err = std.communicate() return out.decode("utf-8").replace("\r", ""), err
Example #2
Source File: ShellExec.py From sublime-3-shell-exec with MIT License | 9 votes |
def command_variables(args, view, command, format=True): if format and args.get("format"): command = args["format"].replace('${input}', command) for region in view.sel(): (row,col) = view.rowcol(view.sel()[0].begin()) command = command.replace('${row}', str(row+1)) command = command.replace('${region}', view.substr(region)) break # packages, platform, file, file_path, file_name, file_base_name, # file_extension, folder, project, project_path, project_name, # project_base_name, project_extension. command = sublime.expand_variables(command, sublime.active_window().extract_variables()) return command
Example #3
Source File: common.py From SublimeOutline with MIT License | 6 votes |
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
Example #4
Source File: standard-format.py From sublime-standard-format with MIT License | 6 votes |
def plugin_loaded(): """ perform some work to set up env correctly. """ global global_path global local_path global settings settings = sublime.load_settings(SETTINGS_FILE) view = sublime.active_window().active_view() if platform != "windows": maybe_path = calculate_user_path() if len(maybe_path) > 0: global_path = maybe_path[0] search_path = generate_search_path(view) local_path = search_path print_status(global_path, search_path)
Example #5
Source File: core.py From Terminus with MIT License | 6 votes |
def _default_config(self): if sys.platform.startswith("win"): return { "name": "Command Prompt", "cmd": "cmd.exe", "env": {} } else: if "SHELL" in os.environ: shell = os.environ["SHELL"] if os.path.basename(shell) == "tcsh": cmd = [shell, "-l"] else: cmd = [shell, "-i", "-l"] else: cmd = ["/bin/bash", "-i", "-l"] return { "name": "Login Shell", "cmd": cmd, "env": {} }
Example #6
Source File: main.py From JavaScriptEnhancements with MIT License | 6 votes |
def plugin_unloaded(): if platform.system() == "Darwin" or platform.system() == "Linux": # When we unload, reset PATH to original value. Otherwise, reloads of this plugin will cause # the PATH to be duplicated. if 'PATH' in fixPathOriginalEnv: os.environ['PATH'] = fixPathOriginalEnv['PATH'] global fixPathSettings fixPathSettings.clear_on_change('fixpath-reload') flow_ide_clients_copy = flow_ide_clients.copy() for root, client in flow_ide_clients_copy.items(): flow_ide_clients[root].stop() flow_cli = FlowCLI(None) flow_cli.stop(root=root)
Example #7
Source File: common.py From SublimeFileBrowser with MIT License | 6 votes |
def is_hidden(self, filename, path, goto=''): if not (path or goto): # special case for ThisPC return False tests = self.view.settings().get('dired_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
Example #8
Source File: ksp_plugin.py From SublimeKSP with GNU General Public License v3.0 | 6 votes |
def play(self, **kwargs): sound_path = os.path.join(self.dir, '{}.wav'.format(kwargs['command'])) if sublime.platform() == "osx": if os.path.isfile(sound_path): call(["afplay", "-v", str(1), sound_path]) if sublime.platform() == "windows": if os.path.isfile(sound_path): winsound.PlaySound(sound_path, winsound.SND_FILENAME | winsound.SND_ASYNC | winsound.SND_NODEFAULT) if sublime.platform() == "linux": if os.path.isfile(sound_path): call(["aplay", sound_path])
Example #9
Source File: core.py From Terminus with MIT License | 6 votes |
def get_config_by_name(self, name): default_config = self.default_config() if name.lower() == "default": return default_config settings = sublime.load_settings("Terminus.sublime-settings") configs = settings.get("shell_configs", []) platform = sublime.platform() for config in configs: if "enable" in config and not config["enable"]: continue if "platforms" in config and platform not in config["platforms"]: continue if name.lower() == config["name"].lower(): return config # last chance if name.lower() == default_config["name"].lower(): return default_config raise Exception("Config {} not found".format(name))
Example #10
Source File: cross_platform_process.py From sublime-gulp with MIT License | 6 votes |
def _pid_exists(self): if not self.pid: return False if sublime.platform() == "windows": taskkill = subprocess.Popen(['C:\\Windows\\system32\\tasklist.exe', '/FI', 'PID eq %s' % self.pid, '/FO', 'CSV'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (stdout, stderr) = taskkill.communicate() failed = taskkill.returncode == 127 or stderr found = str(self.pid) in CrossPlatformCodecs.force_decode(stdout) return found or failed else: try: os.kill(self.pid, 0) except OSError as err: if err.errno == errno.ESRCH: return False elif err.errno == errno.EPERM: return True else: raise else: return True
Example #11
Source File: TabNine.py From tabnine-sublime with MIT License | 6 votes |
def run_tabnine(inheritStdio=False, additionalArgs=[]): binary_dir = os.path.join(TabNineProcess.install_directory, "binaries") settings = sublime.load_settings(SETTINGS_PATH) tabnine_path = settings.get("custom_binary_path") if tabnine_path is None: tabnine_path = get_tabnine_path(binary_dir) args = [tabnine_path, "--client", "sublime"] + additionalArgs log_file_path = settings.get("log_file_path") if log_file_path is not None: args += ["--log-file-path", log_file_path] extra_args = settings.get("extra_args") if extra_args is not None: args += extra_args plugin_version = PACK_MANAGER.get_metadata("TabNine").get('version') if not plugin_version: plugin_version = "Unknown" sublime_version = sublime.version() args += ["--client-metadata", "clientVersion=" + sublime_version, "clientApiVersion=" + sublime_version, "pluginVersion=" + plugin_version] return subprocess.Popen( args, stdin=None if inheritStdio else subprocess.PIPE, stdout=None if inheritStdio else subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=get_startup_info(sublime.platform()))
Example #12
Source File: mixin.py From UnitTesting with MIT License | 6 votes |
def load_stream(self, package, settings): output = settings["output"] if not output or output == "<panel>": output_panel = OutputPanel( 'UnitTesting', file_regex=r'File "([^"]*)", line (\d+)') output_panel.show() stream = output_panel else: if not os.path.isabs(output): if sublime.platform() == "windows": output = output.replace("/", "\\") output = os.path.join(sublime.packages_path(), package, output) if os.path.exists(output): os.remove(output) stream = open(output, "w") return stream
Example #13
Source File: project_manager.py From ProjectManager with MIT License | 6 votes |
def subl(*args): 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' subprocess.Popen([executable_path] + list(args)) def on_activated(): window = sublime.active_window() view = window.active_view() if sublime.platform() == 'windows': # fix focus on windows window.run_command('focus_neighboring_group') window.focus_view(view) sublime_plugin.on_activated(view.id()) sublime.set_timeout_async(lambda: sublime_plugin.on_activated_async(view.id())) sublime.set_timeout(on_activated, 300)
Example #14
Source File: settings.py From sublime-ide-r with MIT License | 6 votes |
def ride_env(self): env = os.environ.copy() paths = self.get("additional_paths", []) if sublime.platform() == "osx" and os.path.isdir("/Library/TeX/texbin"): paths += ["/Library/TeX/texbin"] if paths: sep = ";" if sublime.platform() == "windows" else ":" env["PATH"] = sep.join(paths) + sep + env["PATH"] lang = self.get("lang", None) if lang: env["LANG"] = lang elif "LANG" not in env: env["LANG"] = "en_US.UTF-8" return env
Example #15
Source File: ChromeREPLHelpers.py From ChromeREPL with MIT License | 6 votes |
def get_chrome_process(): user_basename = os.path.basename(get_chrome_path()) is_linux_chrome = sublime.platform() == 'linux' and user_basename != 'chromium-browser' try: basenames_to_check = (['chrome', 'google-chrome'] if is_linux_chrome else [user_basename]) for process in psutil.process_iter(attrs=['exe', 'status']): basename_matches = ('exe' in process.info and process.info['exe'] is not None and os.path.basename(process.info['exe']) in basenames_to_check) is_zombie = 'status' in process.info and process.info['status'] == 'zombie' if basename_matches and not is_zombie: return process except Exception as e: global zombie_message_shown if not zombie_message_shown: sublime.error_message("You may have a zombie Chrome Process. If Chrome won't start, try killing it or restarting your machine") zombie_message_shown = True return None
Example #16
Source File: focus_editor.py From Fuse.SublimePlugin with MIT License | 6 votes |
def tryHandle(self, request): if request.name != "FocusEditor": return False fileName = request.arguments["File"] line = request.arguments["Line"] column = request.arguments["Column"] if not os.path.isfile(fileName): self._returnFailure("File '{}' does not exist".format(fileName), request.id) return True window = self._tryGetWindowFor(request.arguments["Project"]) if window: try: window.open_file( "{}:{}:{}".format(fileName, line, column), sublime.ENCODED_POSITION) if sublime.platform() == "osx": self._focusWindowOSX() self.msgManager.sendResponse(self.interop, request.id, "Success") return True elif sublime.platform() == "windows": self.msgManager.sendResponse(self.interop, request.id, "Success", {"FocusHwnd":window.hwnd()}) return True except Exception as e: self._returnFailure(str(e), request.id) return True return False
Example #17
Source File: RustAutoComplete.py From RustAutoComplete with MIT License | 6 votes |
def run(self, edit): # Get the buffer location in correct format for racer row, col = self.view.rowcol(self.view.sel()[0].begin()) row += 1 results = run_racer(self.view, ["find-definition", str(row), str(col)]) if len(results) == 1: result = results[0] path = result.path # On Windows the racer will return the paths without the drive # letter and we need the letter for the open_file to work. if sublime.platform() == 'windows' and not re.compile('^\w\:').match(path): path = 'c:' + path encoded_path = "{0}:{1}:{2}".format(path, result.row, result.column) self.view.window().open_file(encoded_path, sublime.ENCODED_POSITION)
Example #18
Source File: GotoWindow.py From sublime-goto-window with MIT License | 6 votes |
def on_done(self, selected_index): current_index = self._get_current_index() if selected_index == -1 or current_index == selected_index: return folders = self._get_folders() window_index = folders[selected_index][1] window_to_move_to = sublime.windows()[window_index] self.focus(window_to_move_to) # OS X and Linux require specific workarounds to activate a window # due to this bug: # https://github.com/SublimeTextIssues/Core/issues/444 if sublime.platform() == 'osx': self._osx_focus() elif sublime.platform() == 'linux': self._linux_focus(window_to_move_to)
Example #19
Source File: TabNine.py From tabnine-sublime with MIT License | 6 votes |
def get_tabnine_path(binary_dir): def join_path(*args): return os.path.join(binary_dir, *args) translation = { ("linux", "x32"): "i686-unknown-linux-musl/TabNine", ("linux", "x64"): "x86_64-unknown-linux-musl/TabNine", ("osx", "x32"): "i686-apple-darwin/TabNine", ("osx", "x64"): "x86_64-apple-darwin/TabNine", ("windows", "x32"): "i686-pc-windows-gnu/TabNine.exe", ("windows", "x64"): "x86_64-pc-windows-gnu/TabNine.exe", } versions = os.listdir(binary_dir) versions.sort(key=parse_semver, reverse=True) for version in versions: key = sublime.platform(), sublime.arch() path = join_path(version, translation[key]) if os.path.isfile(path): add_execute_permission(path) print("TabNine: starting version", version) return path
Example #20
Source File: plugin.py From sublime-phpunit with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _get_phpunit_executable(working_dir, include_composer_vendor_dir=True): debug_message('find phpunit executable composer=%s', include_composer_vendor_dir) if include_composer_vendor_dir: if platform() == 'windows': composer_phpunit_executable = os.path.join(working_dir, os.path.join('vendor', 'bin', 'phpunit.bat')) debug_message(' found \'%s\' (windows)', composer_phpunit_executable) else: composer_phpunit_executable = os.path.join(working_dir, os.path.join('vendor', 'bin', 'phpunit')) debug_message(' found \'%s\' (unix)', composer_phpunit_executable) if is_file_executable(composer_phpunit_executable): return composer_phpunit_executable debug_message(' Warning: \'%s\' is not executable!', composer_phpunit_executable) executable = shutil.which('phpunit') debug_message(' found \'%s\' (global)', executable) if executable: return executable else: raise ValueError('phpunit not found')
Example #21
Source File: settings.py From sublime-ide-r with MIT License | 5 votes |
def r_binary(self, default="R"): r_binary = self.get("r_binary", None) if not r_binary and sublime.platform() == "windows": r_binary = self.r_binary_windows() if not r_binary: r_binary = default return r_binary
Example #22
Source File: test_compilation_db.py From EasyClangComplete with MIT License | 5 votes |
def test_strip_wrong_arguments(self): """Test if compilation db is found and flags loaded from arguments.""" include_prefixes = ['-I'] db = CompilationDb( include_prefixes, header_to_source_map=[], lazy_flag_parsing=self.lazy_parsing ) path_to_db = path.join(path.dirname(__file__), 'compilation_db_files', 'arguments') scope = SearchScope(from_folder=path_to_db) if self.lazy_parsing: import sublime if sublime.platform() != 'windows': file_path = path.realpath("/home/user/dummy_lib.cpp") self.assertIn(Flag('', '-Dlib_EXPORTS'), db.get_flags(file_path=file_path, search_scope=scope)) self.assertIn(Flag('', '-fPIC'), db.get_flags(file_path=file_path, search_scope=scope)) # Check that we don't get the 'all' entry. self.assertIsNone(db.get_flags(search_scope=scope)) else: expected = [Flag('-I', path.normpath('/lib_include_dir')), Flag('', '-Dlib_EXPORTS'), Flag('', '-fPIC')] for expected_flag in expected: self.assertIn(expected_flag, db.get_flags(search_scope=scope))
Example #23
Source File: JSCS-Formatter.py From SublimeJSCSFormatter with MIT License | 5 votes |
def get_jscs_path(): platform = sublime.platform() jscs = PluginUtils.get_pref("jscs_path").get(platform) print("Using jscs path on '" + platform + "': " + jscs) return jscs
Example #24
Source File: main.py From JavaScriptEnhancements with MIT License | 5 votes |
def plugin_loaded(): if int(sublime.version()) >= 3124 : if platform.system() == "Darwin" or platform.system() == "Linux": global fixPathSettings fixPathSettings = sublime.load_settings("Preferences.sublime-settings") fixPathSettings.clear_on_change('fixpath-reload') fixPathSettings.add_on_change('fixpath-reload', fixPath) # Save the original environ (particularly the original PATH) to restore later global fixPathOriginalEnv for key in os.environ: fixPathOriginalEnv[key] = os.environ[key] fixPath() debug_mode = javaScriptEnhancements.get("debug_mode") if debug_mode: print(os.environ) sublime.set_timeout_async(delete_temp_files) sublime.set_timeout_async(start, 1000) else: response = sublime.yes_no_cancel_dialog("JavaScript Enhancements plugin requires Sublime Text 3 (build 3124 or newer). Your build is: " + sublime.version() + ". Do you want open the download page?", "Yes, open it", "No") if response == sublime.DIALOG_YES: sublime.active_window().run_command("open_url", args={"url": "https://www.sublimetext.com/3"})
Example #25
Source File: request.py From Requester with MIT License | 5 votes |
def response_tab_bindings(include_delete=False): """Returns string with special key bindings for response tab commands. """ replay = '[cmd+r]' if platform == 'osx' else '[ctrl+r]' nav = '[ctrl+alt+ ←/→]' delete = '[ctrl+alt+delete]' pin = '[cmd+t]' if platform == 'osx' else '[ctrl+t]' save = '[cmd+s]' if platform == 'osx' else '[ctrl+s]' explore = '[cmd+e]' if platform == 'osx' else '[ctrl+e]' if not include_delete: return '{} replay request, {} prev/next request, {} pin/unpin tab, {} save request, {} explore URL'.format( replay, nav, pin, save, explore) s = '{} replay request, {} prev/next request, {} delete request, {} pin/unpin tab, {} save request, {} explore URL' return s.format(replay, nav, delete, pin, save, explore)
Example #26
Source File: base.py From sublime-elasticsearch-client with MIT License | 5 votes |
def track_activate(user_id): analytics.write_key = ANALYTICS_WRITE_KEY analytics.identify(user_id) analytics.track(user_id, "Activate", { "category": "ST3", "label": sublime.platform(), })
Example #27
Source File: ChromeREPLHelpers.py From ChromeREPL with MIT License | 5 votes |
def get_chrome_path(): settings = sublime.load_settings('ChromeREPL.sublime-settings') return os.path.realpath(settings.get('path')[sublime.platform()])
Example #28
Source File: st_color_scheme_matcher.py From sublime-markdown-popups with MIT License | 5 votes |
def sublime_format_path(pth): """Format path for sublime internal use.""" m = re.match(r"^([A-Za-z]{1}):(?:/|\\)(.*)", pth) if sublime.platform() == "windows" and m is not None: pth = m.group(1) + "/" + m.group(2) return pth.replace("\\", "/")
Example #29
Source File: ChromeREPLConnection.py From ChromeREPL with MIT License | 5 votes |
def connect_to_tab(self): self.chrome.get_tabs() # this doesn't return tabs, but updates them internally self.tabs = [tab for tab in self.chrome.tabs if ChromeREPLConnection.is_user_tab(tab)] labels = [tab['title'] for tab in self.tabs] def tab_selected(tab_index): if tab_index == -1: # user cancelled return tab = self.tabs[0] if len(self.tabs) == 1 else self.tabs[tab_index] tab_index = self.chrome.tabs.index(tab) # not using connect_targetID so that chrome stores the connected tab self.chrome.connect(tab_index, False) settings = sublime.load_settings('ChromeREPL.sublime-settings') if settings.get('focus_tab')[sublime.platform()]: ChromeREPLConnection.activate_tab(tab['id']) GotoWindow.focus_window(self.view.window()) try: self.chrome_print("'Sublime Text connected'") except BrokenPipeError as e: sublime.error_message("Sublime could not connect to tab. Did it close?") self.set_tab_status() self.view.window().show_quick_panel(labels, tab_selected)
Example #30
Source File: telemetry.py From sublime-text-plugin with MIT License | 5 votes |
def get_user_agent(): platforms = { 'osx': 'Macintosh', 'linux': 'X11; Linux', 'windows': 'Windows NT 10.0; Win64; x64' } try: version = sublime.load_resource('/'.join(['Packages', __package__, 'VERSION'])) except: version = '1.0.0' return 'Mozilla/5.0 (%s) EmmetTracker/%s' % (platforms.get(sublime.platform()), version.strip())