Search code examples
pythonsublimetext3sublime-text-plugin

How to pass args to an instance of sublime_plugin.WindowCommand?


I create a plug-in for sublime text 3, the designed Command Palette.sublime-commands is as follows:

[
{
    "caption": "Function 1", 
    "args": {parameter:"y"}, 
    "command": "generalfunc"
}, 
{
    "caption": "Function 2", 
    "args": {parameter:"n"}, 
    "command": "generalfunc"
}
]

actually, I want to pass the args to the sublime_plugin instance below:

class GeneralFuncCommand(sublime_plugin.WindowCommand):
    def __init__(self, parameter=None):
        self.parameter = parameter
        super(GeneralFuncCommand, self).__init__()

    def run(self):
        if self.parameter =='y':
            do something
        elif self.parameter =='n':
            do something else
        else:
            pass

What is the proper way to pass args to the GeneralFuncCommand class? Thanks in advance.


Solution

  • I'm a plugin/python newb, but I put something together that works for me.

    The "**args" seems to be the key in the "def" line. Seems to be a wildcard to make all other params available via the args['myparamnamehere'] syntax. I've seen other scripts name that param "**kwargs" so maybe you could google that for more examples (I found tons of examples, but no docs on the how's or the why's of it). There may be a better way, but this is all I found after a couple hours of work on my own project, so I'm just sticking with it.

    class dgReplaceLibCommand(sublime_plugin.TextCommand):
        def run(self, edit, **args):
            if (args['replaceSet'] == "CFML to cfScript"):
                self.cfml_to_cfscript(edit)
    

    I'm guessing your def line needs to look like this...

    def __init__(self, **args):
    

    And then you would access your param like this (again, guessing)...

    self.parameter = args['parameter']
    

    Also, you may need to put quotes around the key "parameter" in your config. I haven't seen too many in the examples that weren't quoted. I.e...

    "args": {"parameter":"y"}, 
    

    Hope this helps!