Hi,
I understand that the key mappings are parsed at load, and therefore cannot expand any variables (e.g. ${file}). This makes sense to avoid repeated parsing of these files.
However, I am trying to write a modified exec command, exec_expand, to pass expanded variables and use in my key mappings. As an example, start with a normal exec command that successfully(*) passes a dummy file name:
{ "keys": ["alt+g"], "command": "exec", "args": { "cmd": ["cmd.exe","/C start /MAX "," O:\\MyProfile\\editor\\confSublime\\Data\\Packages\\User\\scripts\\alt-g ","dummy.txt"], "quiet": true} },
I would like the identical syntax for my exec_expand function, but with variables:
{ "keys": ["alt+g"], "command": "exec_expand", "args": { "cmd": ["cmd.exe","/C start /MAX "," O:\\MyProfile\\editor\\confSublime\\Data\\Packages\\User\\scripts\\alt-g ","${file}"], "quiet": true} },
As I don’t really grok python, I have resorted to AI advice and this is my exec_expand function:
import sublime, sublime_plugin, os, subprocess, datetime, shutil, threading, re
class ExecExpand(sublime_plugin.WindowCommand):
_DOLLAR_RE = re.compile(r"\$(?!\{)([A-Za-z_][A-Za-z0-9_]*)")
def _to_curly(self, s):
return self._DOLLAR_RE.sub(r"${\1}", s)
def run(self, cmd, **kwargs):
if isinstance(cmd, dict):
cmd_str = cmd.get("cmd", "")
kwargs.update({k: v for k, v in cmd.items() if k != "cmd"})
else:
cmd_str = cmd or ""
cmd_str = self._to_curly(cmd_str)
variables = self.window.extract_variables()
expanded = sublime.expand_variables(cmd_str, variables)
# Forward cmd to Sublime's built-in "exec" including any other "args"
exec_kwargs = dict(kwargs)
exec_kwargs["cmd"] = expanded
self.window.run_command("exec", exec_kwargs)
When I try to use the exec_expand key mapping nothing happens, nothing launches, no error messages.
Q1. Is there an easy mistake in my code?
Q2. Is there a better approach - avoiding python as much as possible?
Q3. Does sublime generate error messages - how can I view them?
Kind Regards Gavin Holt
(*) Notes on passing arguments into batch files - excerpt from my batch files
REM Sublime is sending extra characters, possibly when concatenating dictionary
REM If you don't remove these characters the Exist command won't parse and the whole batch fails to launch
REM Allow delayed expansion of variables
setlocal EnableDelayedExpansion
REM Remove extra double quote from %1
set fin=%~1
REM Remove extra space from %1
set fin=!fin: =!
REM Check for a filename
If Not Exist !fin! (
echo Can't find: !fin!
pause
goto End
)