You might be interested by the tabular plugin it allows to align text based on patterns.
In your case if you have
some text %comment
some more text %another comment
&c. %=etc.
with your cursor on the first line you can use 3V
to select the lines you want to treat and then :Tabular /%
and tabular will automatically indent the text like that:
some text %comment
some more text %another comment
&c. %=etc.
The plugin is pretty powerful and can be used to do much more complex operations.
Edit As jjaderberg pointed it out in this case you don't need to select the text: Tabular is pretty clever and can "guess" how to format the text. For example you can use :Tabularize
(without selection neither pattern) and the plugin will still align the comments.
Also an interesting mapping to add to your .vimrc
is:
vnoremap T :Tabular /
This way you can visually select a part of text and use T to easily start tabular.
Edit 2 I was looking around to find fun stuff to do with tabular and I just found out a nice Tim Pope's gist which could be interesting here:
inoremap <silent> % %<Esc>:call <SID>align('%')<CR>a
function! s:align(aa)
let p = '^.*\s'.a:aa.'\s.*$'
if exists(':Tabularize') && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
let column = strlen(substitute(getline('.')[0:col('.')],'[^'.a:aa.']','','g'))
let position = strlen(matchstr(getline('.')[0:col('.')],'.*'.a:aa.':\s*\zs.*'))
exec 'Tabularize/'.a:aa.'/l1'
normal! 0
call search(repeat('[^'.a:aa.']*'.a:aa,column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
endif
endfunction
It maps %
so that when you write several consecutive lines containing a %
, the comments will be automatically aligned on the fly. And when you write a single line with %
it will only be added without more indent.
Note that a possible improvement would be to define the mapping according to the file time so that the correct comment character is mapped for each language.