This is possible, but not the way that you’re trying to do it here. There’s no direct way to infer the file name (or folder name, or some combination thereof because you can select multiple items) that the command is being executed for unless you use a plugin or a command that already has special logic in it for this purpose.
There is undoubtedly a package in package control that does something like this; I think SideBarEnhancements does and there are probably others as well. The remainder of this presumes that you want to set this up yourself instead of going that route, or that you’re at least interested in knowing how you could do it.
For commands in the side bar context menu, when you add the entry to the menu you can add any or all of the arguments files
, dirs
and paths
with values specified as an empty array.
When Sublime executes a command set up this way, it puts the names of all of the selected files in the files
argument, all of the selected folders in the dirs
argument, and both files and folders in the paths
argument. You’re free to use any or all of those as needed. For example, you might want a command that only works on files, only on folders, or both.
You can’t do this directly with the exec
command because that command doesn’t know what to do with an argument named files
, so it will generate an error about that instead. That’s why you need a custom command of some sort to act as an intermediary and gather the file name, then give it to exec
.
For something like that, you can try something like the following:
[
{
"caption": "Open With Finder",
"command": "open_in_finder", "args": {"files": []}
},
]
import sublime
import sublime_plugin
class OpenInFinderCommand(sublime_plugin.WindowCommand):
def run(self, files):
self.window.run_command("exec", {
"cmd": ["open", files[0]],
"shell": False
})
# Make command visible only when there is a single file
def is_visible(self, files):
return len(files) == 1
This implements an open_in_finder
command with a menu entry that tells Sublime that you want to be told the names of all of the files that are currently selected in the side bar when the command triggers. The is_visible
hides the command unless exactly one file is selected, and when the command runs it uses the exec
command to open the file.
If you wanted to be able to open files OR folders in finder, you can replace files
with paths
in both the plugin and the menu entry, which will tell Sublime to provide the name of any selected entry regardless of type. Similarly you could replace it with dirs
to have it only give you the name(s) of folders.
It’s also possible to use two or even all three of them at the same time, if you’re doing something that requires different actions for different things.