Last Updated: February 25, 2016
·
2.206K
· christianromney

Add custom keybindings to Vim by language

Have you ever wanted an easy shortcut for running your tests or launching a REPL for a specific language? When writing Clojure code, for instance, I often want to run 'lein midje'. When writing Ruby code, I want to run 'rake test'. In both cases, I want my normal mode keybinding to be:

<leader>;;

One easy solution is to add a couple Vim filetype plugins:

mkdir -p ~/.vim/ftplugin/clojure ~/.vim/ftplugin/ruby

cat <<EOF > ~/.vim/ftplugin/clojure/testbind.vim
nmap <leader>;; :!lein midje<cr>
EOF
cat <<EOF > ~/.vim/ftplugin/ruby/testbind.vim
nmap <leader>;; :!rake test<cr>
EOF

Now my custom keybinding will run Rake when I edit Ruby files and Leiningen when I edit Clojure.

1 Response
Add your response

It's a good idea to make these mappings local to the buffer:

" ~/.vim/ftplugin/closure/testbind.vim
nmap <buffer> <leader>;; :!lein midje<cr>

That way, if you're in a filetype that you haven't set up like this, you'll get an error instead of executing the wrong command. You can take this one step further by making a global mapping that shows a better error message, or doesn't error out at all:

" ~/.vimrc
nmap <leader>;; :echoerr "No testbind mapping for this buffer"<cr>
" or,
nmap <leader>;; :echomsg "No testbind mapping for this buffer"<cr>
over 1 year ago ·