Categories
Emacs GNU/Linux Free Software & Open Source

PHP syntax error check as you type with Emacs

Emacs php syntax checking on the fly

For those who have to code in PHP, there’s a nice feature in Emacs that makes your coding horror times less stressing and helps you avoid typos and similar dumb errors. For example in the image above, I missed the colon at the end of the line.

Emacs 22.1 comes with flymake mode, a nice tool that makes syntax checking while you type out the file by highlighting the lines with errors and displays the error messages.

You can enable flymake to check PHP syntax by adding the following code on your .emacs or whatever Emacs customizations file you use:

;; Flymake PHP Extension
(require 'flymake)
(unless (fboundp 'flymake-php-init)
  (defun flymake-php-init ()
    (let* ((temp-file (flymake-init-create-temp-buffer-copy
		       'flymake-create-temp-inplace))
	   (local-file (file-relative-name
			temp-file
			(file-name-directory buffer-file-name))))
      (list "php" (list "-f" local-file "-l")))))
(let ((php-ext-re "\\.php[345]?\\'")
      (php-error-re
       "\\(?:Parse\\|Fatal\\) error: \\(.*\\) in \\(.*\\) on line \\([0-9]+\\)"))
  (unless (assoc php-ext-re flymake-allowed-file-name-masks)
    (add-to-list 'flymake-allowed-file-name-masks
		 (list php-ext-re
                       'flymake-php-init
                       'flymake-simple-cleanup
                       'flymake-get-real-file-name))
    (add-to-list 'compilation-error-regexp-alist-alist
		 (list 'compilation-php
                       php-error-re  2 3 nil nil))
    (add-to-list 'compilation-error-regexp-alist 'compilation-php)
    (add-to-list 'flymake-err-line-patterns
		 (list php-error-re 2 3 nil 1))))
;; add php flymake support
(add-hook 'php-mode-hook (lambda () (flymake-mode t)))

Its very nice to have on the fly syntax checking.

By Gabriel Saldaña

Gabriel Saldaña is a web developer, photographer and free software advocate. Connect with him on and Twitter

One reply on “PHP syntax error check as you type with Emacs”

Comments are closed.