2

Recently I was in need of a faster way to format similar code lines according a common character (usually =). For example, I want to format this:

myVar = getMyVar();
myLongerVar = getMyLongerVar();
myYetLongerVar = getMyYetLongerVar();

into that:

myVar          = getMyVar();
myLongerVar    = getMyLongerVar();
myYetLongerVar = getMyYetLongerVar();

then I wrote the following mappings:

" query used to find the common character. In this case i'm setting it to "find the ="
let g:defformatquery = "f="

" set current line as having the longer size till the common character
nnoremap <Leader>gm 0
            \:execute "normal " . g:defformatquery<CR>
            \:let b:epos = getpos(".")[2]<CR>

" format current line according to the position acquired above
nnoremap <Leader>g= 0
            \:execute "normal " . g:defformatquery<CR>hvgeld
            \:execute "normal " . (b:epos - getpos(".")[2]) . "i "<CR>

To use them I have to perform these steps (assuming , is my <Leader>):

  1. position the cursor in the line with the longer text before the = sign (the third line in the example provided, myYetLongerVar)
  2. press: ,gm
  3. for each line I want to format, position the cursor there and press ,g=

Although this works, the process is kinda slow. I want to create a function that would format the entire selected area at once. Then I could just create one map for the function.

Any ideas?

Yuri Ghensev
  • 2,507
  • 4
  • 28
  • 45
  • 2
    Are you aware of tabular.vim? http://stackoverflow.com/questions/8964953/align-text-on-an-equal-sign-with-vim/8964979#8964979 , also http://stackoverflow.com/questions/7248621/align-end-of-line-comments-in-vim/7248713#7248713 – Michael Berkowski Apr 27 '12 at 19:43
  • @Michael very nice! I think that plugin solves my question :) – Yuri Ghensev Apr 27 '12 at 19:48
  • 1
    For small yet relatively universal alignment tricks that work without plugins, see my [answer](http://stackoverflow.com/a/7538363/254635) to the question "[Inserting indentation for columns in Vim](http://stackoverflow.com/q/7529029/254635)". – ib. Apr 28 '12 at 07:00

1 Answers1

1

You should try the Align plugin.

For example, to align some selected lines (selected with v or CTRL-v) according to the = sign, you just type:

:Align =

Or to align from line 34 to 39:

:34,39Align =
Nicolás Ozimica
  • 9,481
  • 5
  • 38
  • 51