my "Open in Vim" OSX service

Many times, when contemplating a grep or a rspec output, I wish I could wink at a certain line and make it open the target file at the appointed line.

I try to work with the keyboard with as little as possible trackpad or mouse gesticulations, but since I'm "contemplating", my rhythm is already lost. So I allowed myself a right-click service.

I double click on the target line in the Terminal.app, right-click then select "Open in Vim" in the contextual menu and it opens the file at the "colon" line for me.

How does it look like behind the scene?

It's an Automator (that robot icon) service, saved under the name "Open in Vim" that chains a Javascript and an Applescript piece of code.

The service has then to be bound from the System Preferences / Keyboard / Shortcuts.

One could even tie a keyboard shortcut for it from there.

Here are the two pieces of code, the Javascript one:


function run(input, parameters) {

  var m = input.toString().match(/([^\s\/:"]*\/[^\s:"]+)(:[0-9]+)?/);

  var m1 = m[1].trim();
  var m2 = m[2] ? "+" + m[2].substring(1) + " " : "";

  return "vim " + m2 + m1;
}

and the Applescript one:


on run {input, parameters}

  tell application "Terminal"
    activate
    tell application "System Events" to key code 36
    delay 0.3
    do script ("" & input) in front window
  end tell

  return input
end run

 

Update 2017-03-31

For those of you using iTerm2, here is a post by Luca Guidi on how to do it: "Click on stack trace to open a file with NeoVim".

Update 2017-04-01

Made Javascript more robust.

Update 2017-04-02

Made Javascript more robust and made sure to send a preliminary return key to the terminal before calling Vim.

Update 2018-06-06

Made Applescript wait before running the vim +... script.