Jun 23, 2009

Make Emacs Warns for Long Lines

On Linux, we can use function font-lock-set-up-width-warning to tell Emacs warning for too long lines in source code:
(add-hook 'c++-mode-hook
'(lambda () (font-lock-set-up-width-warning 80)))
(add-hook 'java-mode-hook
'(lambda () (font-lock-set-up-width-warning 80)))
(add-hook 'python-mode-hook
'(lambda () (font-lock-set-up-width-warning 80)))
On Mac OS X, above method fails. However, With Carbon Emacs or Aquamacs, we can do as follows:
; for CarbonEmacs (MacOSX)
(defun font-lock-width-keyword (width)
"Return a font-lock style keyword for a string beyond width WIDTH
thatuses 'font-lock-warning-face'."
`((,(format "^%s\\(.+\\)" (make-string width ?.))
(1 font-lock-warning-face t))))

(font-lock-add-keywords 'c++-mode (font-lock-width-keyword 80))
(font-lock-add-keywords 'objc-mode (font-lock-width-keyword 80))
(font-lock-add-keywords 'python-mode (font-lock-width-keyword 80))
(font-lock-add-keywords 'java-mode (font-lock-width-keyword 80))
An easier solution for 80-column-rule is lineker. The usage is pretty simple (tested on my IBM T60p, Emacs for Windows): add the following into your .emacs file.
(require 'lineker)
(add-hook 'c-mode-hook 'lineker-mode)
(add-hook 'c++-mode-hook 'lineker-mode)