Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In vim remapping, how do I "capture" and reuse "any" character?

Tags:

vim

In my .vimrc, I have the following which, in insert mode, nicely adds a semi-colon to the end of the line and returns the cursor to its original spot:

inoremap <leader><leader>; <C-o>mp<C-o>A;<C-o>`p

How can I do the same but for ANY/ALL characters? For example, something like this pseudocode:

inoremap <leader><leader><any> <C-o>mp<C-o>A<any><C-o>`p

Or using regex, something like this pseudocode...

inoremap <leader><leader>(\w) <C-o>mp<C-o>A$1<C-o>`p

Is it even possible to capture and reuse like that?

like image 430
pjb Avatar asked Mar 18 '23 09:03

pjb


1 Answers

I think this does what you want:

inoremap <expr> <leader><leader> "<C-o>mp<C-o>A" . (nr2char(getchar())) . "<C-o>`p"

To break it down, there is a command for inoremap called <expr>. This command changes inoremap to look like this: inoremap <expr> {keys} {function} When you press the keys defined in the {keys} section, it will call a function in the {function} section and insert the return value of that function. Anything in quotes in the {function} section will be inserted. So, here is the breakdown of the function section:

"<C-o>mp<C-o>A" . (nr2char(getchar())) . "<C-o>`p"
       ^                   |                 ^
       |-------------------|-----------------|
These just do              |
what the original          |
mapping does               |
                  This just gets a single character
                  from the user and concatenates it to your
                  original mapping, in place of the ';'

Read these for more information on these topics:

:help :map-<expr>
:help getchar()
:help nr2char()

Note: getchar doesn't actually take from the mapping itself, it just prompts the user for a character, then inserts it.

like image 75
EvergreenTree Avatar answered Apr 09 '23 21:04

EvergreenTree