Specific key mapping in Vim

You can set this in your .vimrc as follows:

autocmd FileType ruby map <F2> orequire 'pry'; binding.pry<ESC>
autocmd FileType javascript map <F2> odebugger;<ESC>

When the F2 key is pressed in a *.rb file, "require pry" will be set and "debugger" is set in a *.js file.


The other answer is correct, but not completely correct. You should use the noremap variant of map (see :h noremap), and the proper noremap for whatever mode your are in. If that's insert mode, then it's inoremap <F2> require..., or nnoremap for normal mode, etc.

You can also put those mappings into their own file instead of your vimrc so that you don't need to use autocommands (see :h ftplugin). And (thanks to the comments for reminding me) use <buffer> mappings so they only apply to the file you set them on (see :h <buffer>). In all, this is a good setup for you:

In ~/vim/after/ftplugin/ruby.vim, put the line:

inoremap <buffer> <F2> require 'pry'; binding.pry

and in ~/vim/after/ftplugin/javascript.vim, put the line:

inoremap <buffer> <F2> defbugger;

On windows, the vim directory is instead the vimfiles directory. If you want those mappings in normal mode instead of insert mode, you need to put i or O or another character like that at the front to go into insert mode and put <Esc> on the end to exit insert mode.

Tags:

Vim