Skip to main content.

Using external code beautifiers with Emacs

The following Lisp code is a convenient wrapper to the Lindent script provided with the Linux kernel. For it to work correctly, the Lindent script has to be somewhere on the path. Otherwise modify the lindent-command variable to use an absolute pathname for Lindent.

(defvar lindent-command "Lindent"
  "Command to call to reformat C source code using Linux CodingStyle.")

(defun dzu-lindent-region (start end replace)
  "Call Lindent on region.  Specifying a prefix arg replaces the region."
  (interactive (list (region-beginning) (region-end)
           current-prefix-arg))

  (unless c-indentation-style
    (error "Not editing a C file"))
  ;; Lindent presumes linux style so adjust if neccessary                                              
  (unless (eq c-indentation-style 'linux)
    (c-set-style "linux"))
  (shell-command-on-region start end lindent-command nil replace)
  ;; When we beautify only partially at an indent level we have to add that                            
  ;; manually afterwards.  Fortunately cc-mode can take care of that.                                  
  (when replace
    (indent-region start end)))

You could for example bind this to the f8 key:

(global-set-key [f8] 'dzu-lindent-region)

To use it, simply mark the piece of code in question (between mark and point) and call it (e.g. press f8 when you have bound it to that key). Without a prefix argument, the beautified code will be displayed in the echo area so you can visually compare the original with the resulting code.

Providing a prefix argument with C-u before pressing f8 replaces the original code with the output of Lindent. Note that it is ok only to indent chunks from a source file. In this case the indentation from before the region is used for the result - regardless if it was correct or not.

-- DetlevZundel - 11 Sep 2007