Per-project indentation with php-mode

php-mode supports several different coding styles out of the box:

  • default
  • drupal
  • pear
  • symfony2
  • wordpress

Each coding style has its own settings for indentation. For example, the drupal style uses 2 spaces for indentation, whereas wordpress uses tabs.

By using dir-locals.el, Emacs can automatically set a coding style on a per-project basis. This is /extremely/ helpful when working on different projects that need to be formatted in a particular way.

Here’s an example of a dir-locals.el file that will enable the wordpress coding style for PHP files:

((php-mode . ((php-project-coding-style . wordpress))))

The coding style value doesn’t need to be quoted (otherwise you might see a (wrong-type-argument symbolp wordpress)) error on startup.

If flycheck and phpcs are installed, they can be configured to highlight coding style infractions:

((php-mode . ((php-project-coding-style . wordpress)
              (flycheck-phpcs-standard . "WordPress-VIP")
              (flycheck-checkers . (php-phpcs)))))

The above code will setup php-mode to use tabs, and will also highlight any code that doesn’t meet WordPress VIP standards.

Posted in: Emacs | Comments (1)


Formatting PHP code with Emacs

I was recently asked if Emacs supports formatting PHP code. There are options for other languages, but nothing in the standard release for beautifying PHP.

php-beautifier.el is an extension I created that integrates PHP_Beautifier into Emacs. It can be used to format an entire buffer or a single region.

It also supports phpcbf for fixing coding standards issues.

php-beautifier.el in action

There are two main functions in the extension:

php-beautifier-format-buffer beautifies the entire buffer in one go:

Formatting an entire buffer

php-beautifier-format-region formats a region instead.

Note that PHP_Beautifer checks for a starting <?php tag, so it won't format a region that doesn't contain one.

Full setup and usage instructions are available on the php-beautifier.el project page.

Posted in: Emacs | Comments (0)