Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to halve the number of whitespace at the beginning of each line in Vim?

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 a clarification: This mapping doubles (the && part) the number of whitespace characters at the beginning of each line. Only the whitespace before the first regular character is affected. Current search string is kept in tact (via the _s variable). The cursor position is restored after this transformation (via the _s2 variable).

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 whitespace before the first regular character.

like image 357
Goran Novosel Avatar asked Feb 22 '23 15:02

Goran Novosel


1 Answers

The following substitute command inverses the effect of its counterpart that doubles the leading whitespace.

:%s/^\(\s*\)\1/\1/

A mapping to be constructed for this command needs to follow the same pattern as the one used in the question (except for the substitution to execute, of course). To reduce repetition in the definitions, one can separate the state-preserving code into a small function:

nnoremap <silent> <leader>>    :call PinnedCursorDo('%s/^\s*/&&/')<cr>
nnoremap <silent> <leader><lt> :call PinnedCursorDo('%s/^\(\s*\)\1/\1/')<cr>

function! PinnedCursorDo(cmd)
    let [s, c] = [@/, getpos('.')]
    exe a:cmd
    let @/ = s
    call setpos('.', c)
endfunction
like image 149
ib. Avatar answered Mar 22 '23 23:03

ib.