Sublime Text 2/3 run shell commands On Save #sublimetext

Sublime Text editor is my favorite along with atom. Have you ever really wanted to run a shell command whenever you save a file in Sublime? Like, automatically commit the changes on a github repo or rsync files to a debug server or start a service like php‘s built-in web server? How about all of them together, in bash script of yours? Anyway, It can be done with this really simple plugin (created by Klaas Cuvelier) for Sublime Text 3 (there’s a version for Sublime 2 on packagecontrol.io).

That’s the good news. The bad news are that the plugin waits for stdout to display back on Sublime’s console and that’s something we don’t want it to do. It breaks Sublime’s smooth behavior as it waits for command’s response, and that’s bad.

I modified the plugin a bit so it doesn’t hang but, it needs some refactoring for long computation processes. For example, if I save a file and I have to rsync a large amount of data, close the Sublime editor (or the editor crash), the sub-process will be killed. As a result, no file synchronization will be done. So far I’ve tried to detach the sub-process with start_new_session=True parameter of Popen() with no success. If anyone has an idea, it would be great to share it.

In my example I’m going to use gnome’s notify-send to do the tests and provide a bash script that spawns commands in the background without breaking Sublime’s smooth flow and pop up a gnome notification to inform the developer that the script has finished.

Installation


  1. Clone or download & extract the zip of my my fork , in Sublime’s packages folder, located in your .config directory.
  2. Restart Sublime.

Note: If you are on SBT 2 then search the package control for CommandOnSave.

Note2: If you decide to use Klass’ original repo Don’t forget to comment out the last two lines of CommandOnSave.py

Configuration


  1. Go to PreferencesPackage Settings → Command On Save → Settings - User
  2. Change accordingly the following snippet and paste it.
  3. Create a bash script like the one below
  4. Open a project matching your config and press ctrl + s

In the example bash script below, there is a chain of multiple commands, executed in sub-shell, in the bg and then send some notification with the output of a second command as its body. Change appropriately to you liking, I bet you don’t want to use ping. :P

More commands


To add more commands read the snippet below.

The commands settings-key is an associative array of paths and their commands. Everytime a file is saved, all commands for every matched path-key is executed.

 

Comment: