Ivan Tkalin

I’m a software engineer. I solve problems.

Using console vim as vim:// protocol handler in Ubuntu

Do you want your browser to launch console vim and open specified file on specified line when you click link like this: vim:///etc/hosts&line=10? This article will show how to register console vim as vim:// protocol handler in Ubuntu 11.10. Just follow these steps:

1. Create vim launcher script

We’ll need small vim launcher script, which will handle vim://... uri. As a ruby programmer I wrote this script in Ruby (so it requires Ruby to be installed), but it can be rewritten to Perl/Python or even Bash. What it does, it just retrieves file name and line parameter from URI string and launches gnome-terminal with vim inside, passing file name and line to open. Create /usr/local/bin/cvim file with content:

#! /usr/bin/env ruby

require 'uri'
require 'cgi'

full_path = ARGV[0]

if full_path
  uri = URI::parse(full_path)

  vim_params = %Q["#{uri.path}"]

  if uri.query
    params = CGI::parse(uri.query)
    line = params["line"][0]
  end

  vim_params << " +#{line}" if line
end

`gnome-terminal -x vim #{vim_params}`

Next, give it execute permissions:

sudo chmod a+x /usr/local/bin/cvim

2. Create .desktop file for our new launcher

Now we will create .desktop launcher for our vim launcher, and tell Ubuntu to use this lauchner as vim:// protocol handler. Create ‘/usr/share/applications/cvim.desktop’ file with content:

[Desktop Entry]
Encoding=UTF-8
Name=Vim (Console)
Comment=Edit text files in a console using Vim
Exec=/usr/local/bin/cvim %U
Terminal=false
Type=Application
Icon=/usr/src/vim/runtime/vim48x48.xpm
Categories=Application;Utility;TextEditor;
MimeType=text/plain;x-scheme-handler/vim;
StartupNotify=true
StartupWMClass=CVIM

3. Refresh mime types database

In the file above, line MimeType=text/plain;x-scheme-handler/vim; registers vim:// scheme handler, but to make it work we should update mime types database cache. Execute command:

sudo update-desktop-database

4. Test from terminal

Now everything should work. To test that it works from terminal, launch this command:

xdg-open 'vim:///etc/hosts?line=2'

And it should launch gnome-terminal with vim inside and open file /etc/hosts on line #2. If it works, your browser will do the same when you open link like this.

UPDATE: if you want files to be opened in one vim instance (in the new tab), make /usr/local/bin/cvim file look like this:

#! /usr/bin/env ruby

require 'uri'
require 'cgi'

full_path = ARGV[0]

if full_path
  uri = URI::parse(full_path)
  vim_params = "--remote-tab-silent"

  if uri.query
    params = CGI::parse(uri.query)
    line = params["line"][0]
  end

  vim_params << " +#{line}" if line
  vim_params << %Q[ "#{uri.path}"]
end

`gnome-terminal -x vim --servername VIM #{vim_params}`