How can I configure Vim to set
"require 'pry'; binding.pry"
in Ruby and
"debugger;"
in JavaScript when pressing F2 via key mapping?
Creating a set of key bindings that is familiar, eases the learning curve of any new editor, and the flexibility vim allows in this configuration makes it easy to not only leverage the power of vim, but also make it feel like a familiar old friend.
Silent. Adding <silent> prevents stdout in Vim when a command runs. Sometimes when you execute a command call in Vim, it gets echoed.
1 Answer. Explanation: The map command lets us assign the undefined keys or reassign the defined ones so that when such a key is pressed, it expands to a command sequence.
xmap creates a mapping for just Visual mode whereas vmap creates one for both Visual mode and Select mode. As far as I understand, the intent of Select mode was to make Vim behave just like every other non-modal editor when text is selected, i.e., typing anything immediately replaces the selection with the typed text.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With