2011-07-01

OS X Open With Vim

Edit: After my second OS X post, I went back and created a service to perform Edit with Vim. I actually forgot about the .app that I made with automator. Then I upgraded to Lion and was all sorts of confused when two entries for Edit with Vim popped up in my context menu. Wouldn't you know it? Lion puts all automator Services and Applications into the right click context menu. So I've actually deleted this script and am using the one mentioned here.

OS X comes with vim preinstalled. Nice. It's not that retarded version Ubuntu comes with by default, either. It's the full vim. So then, why the hell can't I right click something, choose open with, and then choose vim? Why can't I pass arguments to the terminal to tell it to run arbitrary commands (such as vim) from the open with dialog?

It appears that OS X only lets you pick Apps as the target application for performing an "Open with". So, to get what I want, I have to use Automator in conjunction with a bash shell script in order to run osascript in order to pop up a new terminal with vim in it and whatever files are selected (or dropped on the app).

Here's what I have in my bash script, aptly named TellTerminal:


This script sends whatever it's arguments are to the Terminal.app and tells it to run them. Then it tells the Terminal.app to activate itself so that it jumps to the foreground. Without this, the terminal will still open, but there's a chance that it will be sitting in the background somewhere. A really, really good chance.

To invoke this script, I had to create an Automator Application (not a workspace, only the .app can be invoked as an application) and add an action 'Run shell script'. This is the shell script that it runs:



This script (which only exists in the Automator app that I've named EditWithVim.app,) loops over all the arguments that were passed to it in order to invoke vim and pass it the quoted file names. This is to avoid having a space within a file name break my script. Also, this script looks for a BashScripts directory in my user's Library directory within the user's home.

Now I can set things to be opened with vim. It's extremely convoluted, but it does seem to be working.

2 comments:

Matt Slay said...

Very nice! I'm kind of a OSX beginner, but I was able to get this working. I'm setting up Rails on my new iMac, and this helps a lot. Thanks for the help.

BTW, is it necessary to use chmod 777 on the bash script to allow it to run? I was getting errors in Automator until I did this.

stephen said...

You can get away with 755 on the script.

I've actually stopped using this method of launching vim and now I use the one outlined here. It eliminates the need for an external script and just has all the code right in the Automator script.