Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim, Tabular and Ruby 1.9 Hashes

Assuming I have the following options Hash as an argument to a method in Ruby 1.9.x:

my_method :arg1,
  some_option: "value 1"
  some_other_option:true
  option_three: 123

Using the Tabular VIM plugin, what would the regular expression be to get the options Hash align like so:

my_method :arg1,
  some_option:       "value 1"
  some_other_option: true
  option_three:      123

The : has to stay attached to the key, unlike with, for example, JSON.

Perhaps a more visually appealing style would be this instead, which looks more aligned:

my_method :arg1,
        some_option: "value 1"
  some_other_option: true
       option_three: 123

Does anyone by any chance know how to accomplish either of these alignments using Tabular?

Thanks!

like image 438
Michael van Rooijen Avatar asked Jan 25 '12 03:01

Michael van Rooijen


2 Answers

In order to get the first alignment, one can use the command

:Tab/\w:\zs/l0l1

For aligning hash keys to the right, it seems inevitable to select only the lines containing them before applying a :Tabular command,

:Tab/\w:\zs/r0l1l0
like image 115
ib. Avatar answered Oct 31 '22 16:10

ib.


I use Tabular a lot but I've never found the occasion to try its "advanced" features. A case similar to your example is presented in :help tabular:

:Tabularize /,/r1c1l0

        Some short phrase , some other phrase
A much longer phrase here , and another long phrase

which makes use of what it calls "format specifiers".

So, applying this command to the options (after visual selection) will do the trick:

:'<,'>Tabularize /:/r1c1l0

my_method :arg1,
        some_option : "value 1"
  some_other_option : true
       option_three : 123

Note to self: play more with Tabular.

like image 20
romainl Avatar answered Oct 31 '22 16:10

romainl