问题
I often insert binding.pry to my ruby files when I debug them. As I use Vim I'd love to automate it to avoid retyping it every time. How could I do it?
The exact sequence I'd like to map is:
- Insert new line.
- Insert
binding.pryto the newly created line. - Return to normal mode.
EDIT: binding.pry is text I want to paste, not a file.
Before insert:
a = 1
b = 2
After insert:
a = 1
binding.pry
b = 2
回答1:
Record a macro (untested)
qq " record macro to register q
o " insert empty line below cursor
esc " exit insert-mode
:r /path/to/binding.pry " insert content of file
esc " cmd-mode
q " end recording
To execute macro, do
@q
Or add the following to your .vimrc file
update
To insert the string binding.pry the mapping becomes:
map ,p obinding.pry<ESC>
回答2:
Easiest is an abbreviation that is triggered from insert mode:
:ia debug <CR>binding.pry
Now, when you type debug, the text binding.pry is inserted on a new line.
回答3:
Based on Fredrik's idea, you can define and store a macro in your .vimrc, say g:
let @g = "Obinding.pry^["
Note that to type the escape character you hit CTRL-V then ESC.
You can then do @g to perform the macro.
In general, if you want to save a macro, one easy way would be to record the macro, say in register q, then do "qp (where q is the macro name) to paste the macro. Then surround it with
let @x = "..."
where x is the macro name you want it to always have and put it in the .vimrc file.
回答4:
Another mapping that will do is:
nnoremap <silent> gb :let a='binding.pry'\|put=a<cr>
回答5:
A great quandary I found myself in. To solve this I placed the following mappings in my .vimrc:
imap <C-b> binding.pry
nnoremap <leader>bp O<% binding.pry %><esc>
The first allows me to use to insert a binding.pry when already in insert mode.
The second lets me use my leader+bp to place a binding.pry above the current line.
回答6:
You can define a shortcut for this purpose with the following key strokes
- :vsplit $MYVIMRC
- i
- nnoremap bi obinding.pry<cr><esc>
- <esc>
- :w
- :source $MYVIMRC
Explaination
- Open your vimrc in a new vertical splitted window
- Switch to insert mode
- Define a mapping for the shortcut 'bi'.
- Leave insert mode
- Save the changes
- Source your vimrc to make the shortcut available
Now, while you in normal mode, the keystrokes <b><i> (one key after each other) will insert 'binding.pry' in a new line under the current line.
Explaination for step 3: nnoremap is the command for mapping keystroke(s) to do some action. 'bi' is the keystroke combination. You can adjust this to your needs. And the rest is a normal edit sequenz on VIM:
- o - Switch to insert mode under the current line
- binding.pry<cr> - is the text which will be writen
- <esc> - Push escape to leave insert mode.
来源:https://stackoverflow.com/questions/17086362/insert-predefined-text-on-keyboard-shortcut