8

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!

Michael van Rooijen
  • 6,683
  • 5
  • 37
  • 33

2 Answers2

13

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
ib.
  • 27,830
  • 11
  • 80
  • 100
  • Note that these commands correctly handle cases when method call arguments or hash values contain symbols (like `:arg1` in the question's example snippet). – ib. Jan 25 '12 at 07:13
  • This only works if there is a single `:` character per line, however – Adam Lassek Jun 14 '18 at 00:14
1

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.

romainl
  • 186,200
  • 21
  • 280
  • 313