Sublime Forum

Run shell command from sidebar menu

#1

Is there a way to run a shell command on a currently selected file in sidebar?
Like standard exec command, but with file path as argument.

[
    {
        "caption": "Do some cool thing with a file",
        "command": "exec",
        "args": {
          "shell_cmd": "bin $path_to_selected_file",
        }
    }
]
0 Likes

#2

Sure. Have a look at Side Bar.sublime-menu https://www.sublimetext.com/docs/menus.html#available_menus
The right clicked file’s absolute path on disk get’s passed as a files argument to the command that is invoked in that context. However, you have to use a custom command that runs the exec command in turn.

3 Likes

#3

OK, I am not familiar with Python, but after some research I made a simple exec wrapper.

That’s how I make it work on macOS.

Cd into: ~/Library/Application Support/Sublime Text 3/Packages/User.

Create a file execa.py:

import os
import sublime
import sublime_plugin

class ExecaCommand(sublime_plugin.WindowCommand):
  def run(self, paths=[], cmd=""):
    if not cmd:
      sublime.error_message("ExecaCommand: Please provide \"cmd\" argument")
      return

    shell_cmd = cmd

    if len(paths) > 0:
      safe_paths = ["\"" + i + "\"" for i in paths]
      shell_cmd = cmd + " " + " ".join(safe_paths)
      cwd = os.path.dirname(paths[0])

    self.window.run_command("exec", {
      "shell_cmd": shell_cmd,
      "working_dir": cwd
    })

Then, create a file Side Bar.sublime-menu:

[
  {
    "caption": "Optimizt",
    "children": [
      {
        "caption": "Optimize Images",
        "command": "execa",
        "args": {
          "paths": [],
          "cmd": "optimizt --verbose",
        }
      },
      {
        "caption": "Create WebP",
        "command": "execa",
        "args": {
          "paths": [],
          "cmd": "optimizt --webp --verbose"
        }
      }
    ]
  }
]

And now I able to run any command with provided paths :tada::sweat_smile::+1:
Hope someone finds this useful.

0 Likes

#4

Huzzah :partying_face: Have fun writing plugins.

0 Likes