Using external code beautifiers with Emacs
The following Lisp code is a convenient wrapper to the
script provided with the Linux kernel. For it to work correctly,
script has to be somewhere on the path. Otherwise
modify the lindent-command variable to use an absolute pathname
(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)
(error "Not editing a C file"))
;; Lindent presumes linux style so adjust if neccessary
(unless (eq c-indentation-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.
(indent-region start end)))
You could for example bind this to the
(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
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
the original code with the output of
. 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.
- 11 Sep 2007