Easy alignment of characters after spaces in vim

I would like to create a mapped vim command that helps me align variable assignments across multiple lines. Imagine that I have the following text in a file:

foo = 1; barbar = 2; asdfasd = 3; jjkjfh = 4; baz = 5; 

If I select multiple lines and use the regex below, noting that column 10 is in a space for all lines, the space after column 10 will be removed to the equal sign.

 :'<,'>s/^\(.\{10}\)\s*\(=.*\)$/\1\2/g 

Here is the result:

 foo = 1; barbar = 2; asdfasd = 3; jjkjfh = 4; baz = 5; 

Is there a way to get the current cursor position (in particular, the column position) when making a selection of a visual block and use this column in a regular expression?

Alternatively, if you can find the max column for any of the equal signs on the selected rows and insert a space so that everyone is equal to the signs aligned in the column, which is preferred to solve the previous problem. Imagine you are quickly converting:

 foo = 1; barbar = 2; asdfasd = 3; jjkjfh = 4; baz = 5; 

in

 foo = 1; barbar = 2; asdfasd = 3; jjkjfh = 4; baz = 5; 

with block selection and key combination.

+7
source share
2 answers

There are two plugins for this: either the older Align - help people align text, eqns, declarations, tables, etc. or tabular .

+5
source

Not completely satisfied with Tabular and Align, I recently created another similar, but simpler plugin called vim-easy-align .

Check out the demo screencast: https://vimeo.com/63506219

In the first case, just visually select the lines and enter the command :EasyAlign= to perform the trick.

If you have defined a mapping such as

 vnoremap <silent> <Enter> :EasyAlign<cr> 

you can do the same with just two keystrokes: Enter and =

The case you mentioned in the comment

 final int foo = 3; public boolean bar = false; 

can be easily aligned using the command:: EasyAlign * \ "or with the above display, Enter, * and a space, which gives

 final int foo = 3; public boolean bar = false; 
+4
source

All Articles