11

Let's say I have a JavaScript in someRandomFile.js and I want to run a command like:

formatMyCode someRandomFile.js

Then inside the file it just indent everything in a nice way.

I want to do format PHP or HTML too. In VIM you can highlight some text and press = and it'll automagically format it (even if it is mixed HTML/PHP/JavaScript). Is there an easy way to do it?

Clay
  • 235
  • 2
  • 8
  • 1
    You can try [`astyle`](http://astyle.sourceforge.net/) (sudo apt-get install astyle), but maybe it is better to use some IDE – Hastur Dec 14 '15 at 08:00

3 Answers3

7

If you like vim you can invoke its action from the command-line.

echo -e "G=gg\n:wq\n" | vim ./myfile.php 

Warning the above command will modify your file without prompting. Do a backup before.
It's possible to find examples integrated with find to accomplish the same work on a bunch of files [0].

Looking beyond it's possible to find a lot of utilities build for this, and this number will continue to grow in time; you can search for their updated versions on internet and you can start for example from:

  • Artistic Style [1], astyle, for C, C++, C++/CLI, Objective‑C, C# and Java programming languages.
  • tidy [2] for Html
  • IDE solutions invoked by command line starting from kate [3] for which there exists just made plug-in; you can built your own indentation scripts [4] too, continuing with UniversalIndentGUI [5], eclipse [5]...
Hastur
  • 18,764
  • 9
  • 52
  • 95
  • I was secretly hoping someone would give a vim example! thank you – Clay Dec 14 '15 at 09:24
  • You're welcome. Just a suggestion, next time try to ask it directly, it can be even faster! (In general try to avoid problems similar to the [xy one](http://xyproblem.info/), it can simplify your and the other's life ;-) ) – Hastur Dec 14 '15 at 09:33
3
vim -c "execute 'normal! =G' | :wq! out.js" input.js

You can also use the alternative syntax + instead of -c. It's the same.

vim +"execute 'normal! =G' | :wq! out.js" input.js
  1. It executes the normal command =G, which will autoformat/indent (=) every line until the end of the file (G).

  2. Then :wq! out.js writes it to a file and quits vim. If you just want to overwrite the same file, then remove the out.js.

Also, you need to have this line in your ~/.vimrc in order for the autoformat indent plugin to work:

filetype plugin indent on

wisbucky
  • 2,928
  • 31
  • 29
1

With eslint, you can

eslint --fix someRandomFile.js

Also works with JSON files. For HTML, consider https://stackoverflow.com/questions/2191989/a-command-line-html-pretty-printer-making-messy-html-readable.

serv-inc
  • 518
  • 1
  • 4
  • 18