Spencer Carnage
Spencer Carnage

Reputation: 2066

A Vim command for formatting objects

Is there an easy shortcut (or plugin) in Vim that can help with formatting code like this:

var obj = {
    one: 1,
    two: 2,
    three: 3,
    four: 4
};

into this?

var obj = {
    one    : 1,
    two    : 2,
    three  : 3,
    four   : 4
};

Upvotes: 4

Views: 117

Answers (2)

user3021843
user3021843

Reputation: 454

You can do this with a vim regular expression. Highlight the lines you can to format with ctrl-V (capital V) then:

:s;\v^(\s*)(\w+)\s*:\s*(\d+,*);\=printf("%s%-7s: %s", submatch(1), submatch(2), submatch(3));g

The :s will be replaced with :'<,'>s, because of visual blockwise mode.

Upvotes: 0

Kent
Kent

Reputation: 195199

there are several align plugins, which could handle this kind of problems very easily:

https://github.com/junegunn/vim-easy-align

https://github.com/godlygeek/tabular

https://github.com/vim-scripts/Align

personally I am using the last one (oldest maybe? ). for your need, I just V select those lines and <leader>t: done!

Upvotes: 3

Related Questions