puk
puk

Reputation: 16782

Pad equality/identity (==/===) with whitespace if necessary (vim)

If there exists a tool to automatically prettify my js code then I would much rather use that package.

I want to expand everything such that a statement like this:

var n=x+(y+(z/k))-123;

turns into:

var n = x + (y + (z / k)) - 123;

However, for the moment, I want to convert all my cramped =, ==, and ===, statements into padded versions of themselves.

I tried using something like :%s/[^ ]==[^ ]/ == /g but the problem with that is that it clips the preceeding and proceeding character.

Upvotes: 2

Views: 119

Answers (2)

johnsyweb
johnsyweb

Reputation: 141860

In Vim, you could use something like:

:%s!\s*\([!<>=/*+-]\+\)\s*! \1 !g

Explanation:

  • s - substitute
  • ! - start pattern
  • \s* - zero or more whitespace
  • \( - start group
  • [!<>=/*+-]\+ - one or more of !<>=/*+-
  • \) - end of group
  • \s* zero or more whitespace
  • ! end of pattern, beginning of replacement
  • <space>\1<space> - the matched group padded by space
  • ! - End of replacement
  • g - globally on a line

But if you want to prettify code and stick to a defined coding standard, you're better off using a tool like Artistic Style.

Upvotes: 4

chown
chown

Reputation: 52778

It would take multiple commands, but you could try something like:

:%s/\([^\s]\)\([+\/()-=]\)/\1 \2/g
:%s/\([+\/()-=]\)\([^\s]\)/\1 \2/g

:%s/\([^\s]\)==/\1 ==/g
:%s/==\([^\s]\)/== \1/g

Then do those last 2 for each: !=, >=, <=, etc..

Upvotes: 2

Related Questions