How to auto format code from the command line?
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?
Solution 1:
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 withUniversalIndentGUI
[5],eclipse
[5]...
Solution 2:
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
It executes the normal command
=G
, which will autoformat/indent (=
) every line until the end of the file (G
).Then
:wq! out.js
writes it to a file and quits vim. If you just want to overwrite the same file, then remove theout.js
.
Also, you need to have this line in your ~/.vimrc
in order for the autoformat indent plugin to work:
filetype plugin indent on
Solution 3:
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.