emacs: Highlighting errors for c, python, and other languages

Posté le mar. 04 avril 2017 dans blog

This is a deprecated article about flymake, you should check for flycheck instead.

Hi! Today we'll see how to highlight syntax errors in emacs, with exemples for C and Python. First you should learn about flymake-mode In a nutshell Flymake is a minor mode to perform on the fly checks on your files. It can run any external syntax checker by different means, I let you check out the documentation. Quick and easy setup to highlight C syntax : You already have a Makefile, that's good, so you just have to add a new rule to your Makefile, named 'check-syntax':

check-syntax:
    gcc -o /dev/null -D$(DEFINE) $(CFLAGS) -S ${CHK_SOURCES}

You can fix my -D\$(DEFINE) \$(CFLAGS) to match your compile options ... Then open a .c file in your project, and if you .emacs file don't automatically start flymake-mode, type 'M-x flymake-mode' and enjoy error highlighting ! Next trick is, if you're using a non graphical emacs, you don't have, by default, the error message, so i's a bit anying... So you'll add some lines in you .emacs and a file in you .emacs.d First, download flymake-cursor.el here http://www.emacswiki.org/emacs/download/flymake-cursor.el and put it in your \~/.emacs.d/ Then in your .emacs, add :

(require 'cl)
(require 'flymake-cursor)

Now, when you stop your cursor on an error, the message should appear in the minibuffer. Last trick, for Python developers, how to use flymake-mode with pyflakes ? Just add this to you .emacs file, and tweak it if you want. You should install pyflakes in order to make it work.

;; aptitude install pyflakes to check python code
(require 'flymake-cursor)
(global-set-key [f4] 'flymake-goto-next-error)

(when (load "flymake" t)
  (defun flymake-pyflakes-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 "pyflakes" (list local-file))))

  (add-to-list 'flymake-allowed-file-name-masks
               '("\\.py\\'" flymake-pyflakes-init)))

(add-hook 'find-file-hook 'flymake-find-file-hook)

Bonus trick you should try : Replace "pyflakes" in (list "pyflakes" (list local-file)))) to a shell script of you own, running pyflakes, pep8, etc...as I just found here : http://stackoverflow.com/questions/1259873/how-can-i-use-emacs-flymake-mode-for-python-with-pyflakes-and-pylint-checking-cod

#!/bin/bash

epylint "$1" 2>/dev/null
pyflakes "$1"
pep8 --ignore=E221,E701,E202 --repeat "$1"
true

Enjoy!