The default VIM indentation commands indent by shiftwidth spaces
e.g.
>> Indent line by shiftwidth spaces
<< De-indent line by shiftwidth spaces
Is there any way to indent with one or n (where n != shiftwidth) space(s)?
One way to do that is to vertically select a column in the block with Ctrl+V then, I to insert vertically and then type a space and <Esc>. But is there a better way?
I’m not sure that there is a better way. But, there are a few ways that you could do it (that I can think of anyway)…
Your Visual Block Solution
Like you said: press
Ctl-Vselect the lines you want, pressIto insert, and enter the number of spaces.Search
Similar to the above but a little more flexible – you can use with with the ‘select paragraph’
vipcommand, or any range really: pressvorvipor what have you to select the range, and the type:s/^/{n spaces}where {n spaces} is the number of spaces you want to insert.Its a little more verbose, but works pretty well for pretty much any range. Heck, if you wanted to do the whole file you could do
Ctl-A(OS dependent) and indent the whole file (or just skip the whole visual mode thing and just do it command mode…as in:1,$s/^/{n spaces}Note that you don’t have to include the third slash in s/// since you aren’t putting any switches at the end of the search.
Global
Maybe you want to only indent lines that match some pattern. Say…all lines that contain foo. No problem: type
:g/foo/s/^/{n spaces}Global is especially handy if its multi-line sections with a similar pattern. You can just escape into normal mode land and select the lines you want and indent accordingly:
:g/foo/norm Vjj:s/^/{n spaces}Ctl-V{Enter}. Little more complicated with that extraCtl-V{Enter}at the end but useful under certain circumstances.Use tabstop and shiftwidth
Yes, if your doing it a lot – I’d do
:set ts=2and:set etand:set sw=2and use>>and<<every which way…Make a Function
Okay, so still not brief enough and for whatever reason you need to do this a lot and you can’t abide messing with
sw,etandtssettings. No problem, just write up a quick function and give it alocalleadermapping:Maybe just knowing more than one way to do this is better than only knowing one? After all, sometimes the best solution depends on the problem 🙂