我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用sublime.expand_variables()。
def __replace_wildcard_if_needed(self, line): """Replace wildcards in a line if they are present there. Args: line (str): line possibly with wildcards in it Returns: str: line with replaced wildcards """ res = sublime.expand_variables(line, self._wildcard_values) if Wildcards.HOME_PATH in res: # replace '~' by full home path. Leave everything else intact. prefix_idx = res.index(Wildcards.HOME_PATH) prefix = res[:prefix_idx] home_path = path.expanduser(res[prefix_idx:prefix_idx + 1]) res = prefix + home_path + res[prefix_idx + 1:] if res != line: log.debug("populated '%s' to '%s'", line, res) return res
def replace_variables(value, variables): if hasattr(sublime, 'expand_variables'): # ST3, Build 3068 # stringify dict for k in variables.keys(): variables[k] = str(variables[k]); return sublime.expand_variables(value, variables) else: # sort keys after length, to get $file_path before $file keys = list(variables.keys()) keys.sort(key=len, reverse=True) for k in keys: key = "${%s}" % k if key in value: value = value.replace(key, str(variables[k])) return value # ##################################################### LIST utils #########
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)
def transform_aliases(self, string): """Transform aliases using the settings and the default variables It's recursive, so you can use aliases *in* your aliases' values """ def has_unescaped_dollar(string): start = 0 while True: index = string.find('$', start) if index < 0: return False elif string[index-1] == '\\': start = index + 1 else: return True string = string.replace('$$', '\\$') vars = self.window.extract_variables() vars.update(get_settings().get('aliases')) inifinite_loop_counter = 0 while has_unescaped_dollar(string): inifinite_loop_counter += 1 if inifinite_loop_counter > 100: sublime.error_message("Infinite loop: you better check your " "aliases, they're calling each other " "over and over again.") if get_settings().get('open_help_on_alias_infinite_loop', True) is True: sublime.run_command('open_url', { 'url': 'https://github.com/math2001/ ' 'FileManager/wiki/Aliases ' '#watch-out-for-infinite-loops' }) return string string = sublime.expand_variables(string, vars) return string
def _expand(self, kwargs): env = self.window.extract_variables() rv = kwargs.copy() for key in ['pytest', 'target', 'working_dir']: rv[key] = sublime.expand_variables(kwargs[key], env) return rv
def _configure(window): try: cmake = window.project_data()["settings"]["cmake"] build_folder = cmake["build_folder"] build_folder = sublime.expand_variables( build_folder, window.extract_variables()) if os.path.exists(build_folder): window.run_command("cmake_configure") except Exception: pass
def _on_done_select_scheme(cls, index): if index == -1: cls._is_selecting = False return cls.name = cls.items[index][0] if cls.name == "INVALID SCHEME": cls._is_selecting = False return cls.build_folder_pre_expansion = cls.schemes[index]["build_folder"] cls.build_folder = sublime.expand_variables( cls.build_folder_pre_expansion, cls.window.extract_variables()) cls.command_line_overrides = cls.schemes[index].get( "command_line_overrides", {}) cls._select_generator()
def is_enabled(self): try: build_folder = self.window.project_data()["settings"]["cmake"]["build_folder"] build_folder = sublime.expand_variables(build_folder, self.window.extract_variables()) return os.path.exists(os.path.join(build_folder, "CMakeCache.txt")) except Exception as e: return False
def run(self): build_folder = self.window.project_data()["settings"]["cmake"]["build_folder"] build_folder = sublime.expand_variables(build_folder, self.window.extract_variables()) self.window.open_file(os.path.join(build_folder, "CMakeCache.txt")) self.window.run_command("show_overlay", args={"overlay": "goto", "text": "@"})
def is_enabled(self): try: build_folder = self.window.project_data()["settings"]["cmake"]["build_folder"] build_folder = sublime.expand_variables(build_folder, self.window.extract_variables()) return os.path.exists(build_folder) except Exception as e: return False
def run(self): build_folder = self.window.project_data()["settings"]["cmake"]["build_folder"] build_folder = sublime.expand_variables(build_folder, self.window.extract_variables()) self.window.run_command('open_dir', args={'dir': os.path.realpath(build_folder)})
def is_enabled(self): """You may only run this command if there's a `build_folder` with a `CMakeCache.txt` file in it. That's when we assume that the project has been configured.""" try: build_folder = self.window.project_data()["settings"]["cmake"]["build_folder"] build_folder = sublime.expand_variables(build_folder, self.window.extract_variables()) return os.path.exists(os.path.join(build_folder, "CMakeCache.txt")) except Exception as e: return False
def is_enabled(self): try: build_folder = self.window.project_data()["settings"]["cmake"]["build_folder"] build_folder = sublime.expand_variables(build_folder, self.window.extract_variables()) return os.path.exists(os.path.join(build_folder, "CMakeCache.txt")) except Exception as e: return False return True
def __init__(self, window): super(CMakeGenerator, self).__init__() data = window.project_data()["settings"]["cmake"] self.build_folder_pre_expansion = data["build_folder"] data = sublime.expand_variables(data, window.extract_variables()) self.build_folder = self._pop(data, "build_folder") if not self.build_folder: raise KeyError('missing required key "build_folder"') self.build_folder = os.path.abspath(self.build_folder)\ .replace("\\", "/") pfn = window.project_file_name() if not pfn: self.source_folder = window.extract_variables()["folder"] else: self.source_folder = os.path.dirname(pfn) while os.path.isfile( os.path.join(self.source_folder, "..", "CMakeLists.txt")): self.source_folder = os.path.join(self.source_folder, "..") self.source_folder = os.path.abspath(self.source_folder) self.source_folder = self.source_folder.replace("\\", "/") self.command_line_overrides = self._pop( data, "command_line_overrides", {}) self.filter_targets = self._pop(data, "filter_targets", []) self.configurations = self._pop(data, "configurations", []) self.env = self._pop(data, "env", {}) self.target_architecture = self._pop( data, "target_architecture", "x86") self.visual_studio_versions = self._pop( data, "visual_studio_versions", [15, 14]) self.window = window assert self.build_folder
def create_sublime_build_system(self): view = self.window.active_view() if not view: sublime.error_message('Could not get the active view!') name = get_setting(view, 'generated_name_for_build_system') if not name: sublime.error_message('Could not find the key ' '"generated_name_for_build_system"' ' in the settings!') name = sublime.expand_variables(name, self.window.extract_variables()) build_system = { 'name': name, 'shell_cmd': self.shell_cmd(), 'working_dir': self.build_folder_pre_expansion, 'variants': self.variants() } file_regex = self.file_regex() if file_regex: build_system['file_regex'] = file_regex syntax = self.syntax() if syntax: build_system['syntax'] = syntax env = self.get_env() if env: build_system['env'] = env return build_system
def start_client(window: sublime.Window, config: ClientConfig): project_path = get_project_path(window) if project_path is None: return None if settings.show_status_messages: window.status_message("Starting " + config.name + "...") debug("starting in", project_path) # Create a dictionary of Sublime Text variables variables = window.extract_variables() # Expand language server command line environment variables expanded_args = list( sublime.expand_variables(os.path.expanduser(arg), variables) for arg in config.binary_args ) # Override OS environment variables env = os.environ.copy() for var, value in config.env.items(): # Expand both ST and OS environment variables env[var] = os.path.expandvars(sublime.expand_variables(value, variables)) client = start_server(expanded_args, project_path, env) if not client: window.status_message("Could not start " + config.name + ", disabling") debug("Could not start", config.binary_args, ", disabling") return None initializeParams = { "processId": client.process.pid, "rootUri": filename_to_uri(project_path), "rootPath": project_path, "capabilities": { "textDocument": { "completion": { "completionItem": { "snippetSupport": True } }, "synchronization": { "didSave": True } }, "workspace": { "applyEdit": True } } } if config.init_options: initializeParams['initializationOptions'] = config.init_options client.send_request( Request.initialize(initializeParams), lambda result: handle_initialize_result(result, client, window, config)) return client
def _diagnose(self, edit): self.table = [] try: output = check_output("cmake --version").splitlines()[0][14:] except Exception as e: self.table.append(["cmake present", False, "Install cmake"]) return else: self.table.append(["cmake version", output, ""]) try: server_mode = capabilities("serverMode") self.table.append(["server mode", server_mode, ""]) except Exception as e: self.table.append(["server mode", False, "Have cmake version >= 3.7"]) project = self.view.window().project_data() project_filename = self.view.window().project_file_name() if project_filename: self.table.append(["project file", project_filename, ""]) else: self.table.append(["project file", "NOT FOUND", "Open a .sublime-project"]) self.error_count += 1 return cmake = project.get("settings", {}).get("cmake", None) if cmake: cmake = sublime.expand_variables( cmake, self.view.window().extract_variables()) buildFolder = cmake['build_folder'] if buildFolder: self.table.append(["cmake dictionary present in settings", True, ""]) cache_file = os.path.join(buildFolder, 'CMakeCache.txt') if os.path.isfile(cache_file): self.table.append([ "CMakeCache.txt file present", True, "You may run the Write Build Targets command"]) else: self.table.append(["CMakeCache.txt file present", False, "Run the Configure command"]) self.error_count += 1 return else: self.table.append(["build_folder present in cmake dictionary", False, "Write a build_folder key"]) self.error_count += 1 else: self.table.append(["cmake dictionary present in settings", False, "Create a cmake dictionary in your settings"]) return