import sublime
import sublime_plugin
from .settings import r_box_settings
from .script_mixin import ScriptMixin


class RBoxExecCommand(ScriptMixin, sublime_plugin.WindowCommand):
    def run(self, cmd, cwd=None):
        if cwd:
            working_dir = cwd
        else:
            working_dir = self.find_working_dir()

        custom_env = self.custom_env()

        extracted_variables = self.window.extract_variables()
        cmd = sublime.expand_variables(cmd, extracted_variables)

        self.window.run_command(
            "exec",
            {
                "cmd": [r_box_settings.rscript_binary(), "-e", cmd],
                "working_dir": working_dir,
                "env": {"PATH": custom_env["PATH"]}
            })

@@ -1,19 +1,4 @@
-import sublime%0A
 impo
@@ -15,16 +15,16 @@
 _plugin%0A
+
 from .se
@@ -92,16 +92,464 @@
 Mixin%0A%0A%0A
+def escape_dquote(cmd):%0A    cmd = cmd.replace('%5C%5C', '%5C%5C%5C%5C')%0A    cmd = cmd.replace('%22', '%5C%5C%22')%0A    return cmd%0A%0A%0Adef escape_squote(cmd):%0A    cmd = cmd.replace('%5C%5C', '%5C%5C%5C%5C')%0A    cmd = cmd.replace(%22%5C'%22, %22%5C'%22)%0A    return cmd%0A%0A%0Adef replace_variable(cmd, var, value):%0A    cmd = cmd.replace(%22%5C%22%22 + var + %22%5C%22%22, %22%5C%22%22 + escape_dquote(value) + %22%5C%22%22)%0A    cmd = cmd.replace(%22'%22 + var + %22'%22, %22'%22 + escape_squote(value) + %22'%22)%0A    return cmd.replace(var, value)%0A%0A%0A
 class RB
@@ -865,63 +865,109 @@
     
-cmd = sublime.expand_variables(cmd, extracted_variables
+for var, value in extracted_variables.items():%0A            cmd = replace_variable(cmd, %22$%22+var, value
 )%0A%0A 

improve the way expanding variables