Sunday, May 2, 2010

Which is the best way of doing some mapping reuse?

Hi all :)

Usually in my scripts I use constructs like this (just an example):

nnoremap <silent><buffer> <LocalLeader>KEY m'gg"+yG''
imap <silent><buffer> <LocalLeader>KEY <C-\><C-O><LocalLeader>KEY
...maybe more mappings here for other modes...

This way I put the logic only in one map (the nnoremap) one, and reuse
it in the other mappings.

Of course this doesn't work because after the <C-\><C-O> only the m'
command is executed, Vim returns to insert mode and gg"+yG'' is inserted
as typed text.

There are plenty of solutions to this problem, and I don't know which
one is better/shorter/more clever.

First one is copying and pasting the map, but that is not good for
maintenance, because if you have to modify the mapping later, you have
to do it in probably many lines:

nnoremap <silent><buffer> <LocalLeader>KEY m'gg"+yG''
inoremap <silent><buffer> <LocalLeader>KEY <Esc>m'gg"+yG''i

I don't like this, really.

Second solution is using a function:

function! s:whatever()
normal! m'gg"+yG''
endfunction
nnoremap <buffer><silent> <LocalLeader>KEY :call <SID>whatever()<CR>
inoremap <buffer><silent> <LocalLeader>KEY <C-R>=<SID>whatever()<CR>

Far from elegant, I think, but it should work.

Third solution, probably the best?:

nnoremap <silent><buffer> <LocalLeader>KEY m'gg"+yG''
imap <silent><buffer> <LocalLeader>KEY <C-\><C-N><LocalLeader>KEYi

According to the help, the above insert mode mapping won't work in ex
mode. Not a big problem, though, for my needs.

Any better way of achieving the same? Any problem I'm not aware of?

Thanks in advance!

--
Raúl "DervishD" Núñez de Arenas Coronado
Linux Registered User 88736 | http://www.dervishd.net
The revolution will not be televised

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: