Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting PHP Code within Vim

I'm currently using Vim as a lightweight IDE. I have NERDTree, bufexplorer, supertab, and ctags plugins which do almost everything I want. Only big thing missing for me is auto code formatting.

I'm working with some messy PHP code which has inconsistent indenting and code formatting, ideally I could highlight the code I want formatted (whole files would be fine too) and run a command to tidy it.

Does anybody have a nice solution for this working in Vim?

like image 766
gacrux Avatar asked May 13 '09 13:05

gacrux


People also ask

How do I format a PHP file?

Add right click menu option for Format HTML in PHP. Add keybind Ctrl + Alt + F to format HTML in a PHP file.


5 Answers

Quick way to fix PHP indentation in vim is to visually select the lines you want to work with using shift-v, and then press equals (=) to trigger auto-formatting.

As for other formatting issues you're probably looking at employing some regex search and replaces, such as :%s/^M/\r/g (that's ctrl-V ctrl-m, not caret-M) to fix line endings

like image 174
Wes Mason Avatar answered Sep 29 '22 04:09

Wes Mason


Enter normal mode in vim and then type

1GVG=
like image 33
wormhit Avatar answered Sep 29 '22 06:09

wormhit


Format in PSR-2 style

For the new standard Coding Style Guide PSR-2 use the PHP-CS-Fixer.

There is a Vim plugin: Vim-php-cs-fixer

How to install:

Install PHP-CS-Fixer (globally with Composer):

composer global require friendsofphp/php-cs-fixer

Then add the Vim plugin (Pathogen):

cd ~/.vim/bundle
git clone [email protected]:stephpy/vim-php-cs-fixer.git

Restart Vim.

Default mapping:

<leader>pcd " For directory
<leader>pcf " For flie
like image 39
Janghou Avatar answered Sep 29 '22 06:09

Janghou


There is a vim plugin that enables formatting on your code from within vim. It's called vim-autoformat and you can read about it and download it here:

https://github.com/vim-autoformat/vim-autoformat

It integrates external code-formatting programs into vim. When this plugin is installed, you only have to install an external code formatter to get everything to work out of the box. It supports the php formatter phpCB, which is the best php formatter i've seen so far.

UPDATE: phpCB is not supported anymore, due to code breaking behaviour. However, vim's indentfile is always used as fallback, allowing you to at least indent your code when there's is no formatter available.

like image 33
chtenb Avatar answered Sep 29 '22 05:09

chtenb


The vim website is not the easiest to navigate, but there is a wealth of chewy nougat center there.

For instance I found this php indenting script there. Give it a try.

like image 42
Whaledawg Avatar answered Sep 29 '22 05:09

Whaledawg