Sunday, August 14, 2011

Re: Align one line to another

On 08/14/2011 11:42 AM, Tim Johnson wrote:
> I'd like to find a way to align one or more lines with the same
> indentation as (say) the previous line:
> Example :
> """Main entry point for this module.
> Process all.
> Delete all."""
> To
> """Main entry point for this module.
> Process all.
> Delete all."""

There are lots of ways to do this, so I'll toss a couple out
there and you can pick & choose depending on your needs.

The first & easiest (assuming the first/"previous" line is an
even multiple of 'shiftwidth' and corresponds to your 'expandtab'
settings) is to just use the ">" or "<" commands to shift over
the range. In the above example, I'd select the 2nd & 3rd lines
and hit ">" to shift them right one. If I needed multiple shifts
to get them into position, I'd then hit "." (period) to repeat
the shift until they're in place.

If the 1st/"previous" line's leading whitespace *isn't* a
multiple of 'sw', making the previous method less helpful, then
I'd consider using visual-block mode to select the left-hand
column of the stuff to indent and then hit "I" (capital-eye) to
insert at the beginning of the block. Put in the expected/proper
indentation, and then hit <esc> which will put that indentation
on all the lines. If the indentation of the 1st/"previous" line
is a bit crazy (say, a sick mixture of tabs/spaces), then you
could copy that indentation from the first line and then after
hitting "I" in visual-block-mode, use control+R followed by a
double-quote to insert the crazy indentation.

Both of those are somewhat manual. If you want to create a
mapping, you could do something like

:vnoremap <f4> :'<+1,'>s/^\s*/\=matchstr(getline("'<"),
'^\s*')<cr>

which would allow you to visually select the lines in question.
The mapping will then sniff the indentation of the first line you
selected and then apply it to all the lines afterward.

Finally, if you have oodles of these in your file and you don't
want to visually select each piece manually, you can break out
the nuclear option...something like

:g/^\s*"""/ka|+,/"""/s/^\s*/\=matchstr(getline("'a"), '^\s*')

(this burns the "a" mark, so adjust the "ka" and "'a" accordingly
if you don't want to tromp them) which will search for every line
beginning with three double-quotes (with optionally leading
whitespace) and then adjust from the following line ("+") through
the next match of three double-quotes and pull down the
indentation from the first/"previous" line. If you don't want to
burn ANY marks, it might be doable with

:g/^\s*"""/+,/"""/s/^\s*/\=matchstr(getline(line('.')-1), '^\s*')

So there you have a whole mess of options depending on the time,
energy, and enormity of the task at hand. :) Hope it helps,

-tim


--
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: