Can someone tell me how to do the opposite of this mapping in Vim:
nnoremap <leader>iw :let _s=@/<Bar>:let _s2=line(".")<Bar>:%s/^\s*/&&/ge<Bar>:let @/=_s<Bar>:nohl<Bar>exe ':'._s2<CR>
As clarification, this mapping doubles (&&
part) the number of whitespace at the beginning of each line.
Only whitespaces before first regular character are affected.
Current search string is kept (variable _s
).
Position is restored after this transformation (variable _s2
)
So basically I'm searching for a mapping that will undo this one if they are executed one after another.
I'm having trouble in figuring out how to limit this new operation to work only on whitespaces before first regular character.
Your original substitution is this (I have replaced the
/
delimiters with#
for readability):And here is my proposed inverse substitution (take a deep breath...):
Let's say the matched string (
submatch(0)
) containsn
whitespace characters. What I am doing is calculating half this number (n/2
=string(float2nr(len(submatch(0))/2))
) and then extracting that many characters from the match (essentiallymatchstr(n/2)
). This ensures we get precisely half the whitespace we started with (which may be a mixture of spaces and tabs).If you know the whitespace will contain ONLY spaces or ONLY tabs, this could be simplified somewhat, for example:
On another note, I would recommend reformulating your maps to make them more readable and therefore easier to modify and maintain. My approach would be to define two functions:
Note that the
get/set
pos/reg
functions are a much more robust way of maintaining cursor position and register. You can then map these functions as you wish:Hope that helps!
The following substitute command inverses the effect of its counterpart doubling leading whitespace.
A mapping to be constructed for this command needs to follow the same pattern as the one used in the question statement (except for the substitution to execute, of course). To reduce repetition in definitions, one can separate the state-preserving code into a small function: