Thursday, May 2, 2024
8
rated 0 times [  8] [ 0]  / answers: 1 / hits: 3970  / 2 Years ago, fri, july 8, 2022, 6:08:01

Given a directory containing a source tree, is there a simple way from command-line to replace each source file with its beautifully reformatted equivalent?



Keep in mind that usually a source tree for a project also contains files which are not source, and the sources themselves could be in different languages.



I'm looking for some tool that supports as many languages as possible, because a project usually contains sources in many different languages. In particular, I'd be looking for something supporting xml/html, javascript, ruby, and java.


More From » software-recommendation

 Answers
4

You could use vim in ex and command mode, from the terminal.



To indent a single file:



vim -c "normal gg=G" -e <file-to-indent> <<'EOF'
:wq
EOF


To indent files recursively, create the following script:



indent-with-vim.sh



vim -c "normal gg=G" -e $1 <<'EOF'
:wq
EOF


Now, type:



$ chmod u+x indent-with-vim.sh
$ find . | xargs -I {} ./indent-with-vim.sh {}


Vim will do its best to reindent the files. You may improve some specific file types.



For XML:




  • Install xmllint
    Add to your .vimrc



    au FileType xml setlocal equalprg=xmllint --format --recover - 2>/dev/null



To improve PHP formatting:



Download http://www.vim.org/scripts/download_script.php?src_id=15001
(it will download a file named php.vim)



Create the following directories on your home:



~/.vim/indent



And copy php.vim to ~/.vim/indent



If you are not satisfied with the result for any file type, you may look for alternatives on the web (like htb for HTML, https://github.com/vim-ruby/vim-ruby for improvements for Ruby, and so on).



Either way, you'd use or the .vimrc technique or the foo.vim indent file to improve the indentation.



Also, you can change the find parameters to apply to some specific types only, such as:



find . -iname "*.html" -or -iname "*.xml"

[#40779] Sunday, July 10, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
doredtness

Total Points: 153
Total Questions: 113
Total Answers: 106

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
;