Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific key mapping in Vim

Tags:

vim

How can I configure Vim to set

"require 'pry'; binding.pry"

in Ruby and

"debugger;"

in JavaScript when pressing F2 via key mapping?

like image 246
D.W Avatar asked Mar 04 '20 19:03

D.W


People also ask

Does vim allow for custom key bindings?

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.

What is the silent key in vim?

Silent. Adding <silent> prevents stdout in Vim when a command runs. Sometimes when you execute a command call in Vim, it gets echoed.

Which command is used for mapping keys of a keyboard *?

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.

What is XMAP in vim?

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.


2 Answers

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.

like image 83
Raswidr Avatar answered Oct 13 '22 22:10

Raswidr


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.

like image 36
doopNudles Avatar answered Oct 14 '22 00:10

doopNudles