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:

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

  (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" 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 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 at that point is used for the result.

-- DetlevZundel - 11 Sep 2007