How can I apply the new Emacs C style to reformat all source files?

I would like to reformat all my source files using the google formatting function for emacs: google-c-style.el (see here ).

How can I apply this function to all source files at once, so that they are all formatted and indented correctly in accordance with Google style?

+7
code-formatting emacs lisp elisp
source share
4 answers

There are several parts:

  • you need to get started with EMACS functions to perform all the necessary reformatting. indent-region is the start, but you can also refuse it or any other things.
  • you need to call them in each file, and since indentation functions work in ranges, you need a function that sets a label to cover the entire file: mark-whole-buffer .
  • you need to call EMACS for each file: this means calling emacs with the -batch file.

There are a couple of good blog posts about it here and here .

+9
source share

I have done this before using the macro defined by the keyboard. I would upload all the files to emacs (something like find . -name "*.cpp" | xargs emacs ) and then enter the following keys. I annotated each key combination with what it does.

 Cx-( 'Begin recording macro M-< 'Go to start of file C-space 'Mark current location (now start of file) M-> 'Go to end of file Mx indent-region 'Indent entire file according to coding style Cx Cs 'Save the current buffer Cx Ck 'Close the current buffer Cx-) 'End recording macro 

Now you can run this in the buffer by typing Cx e . If you have downloaded multiple files, you can run something like Cu 100 Cx e to run it on 100 files. If this is more than the number of files, this is normal, you just get some β€œcall” or other error that you can ignore after all the processing is complete.

+3
source share

I believe this script does not reformat. Instead, this is an example of how to create a custom β€œstyle,” as described in: CC Mode Guide - Styles

The CC mode guide also says:

If you want to reformat the old code, you are probably better off using another tool, for example. GNU indent, which has more powerful reformatting capabilities than CC Mode.

CC Mode Guide - Limitations and Known Errors

+2
source share

If you want to mark the source files in a processed buffer and then run the function for formatting, you can do something like this:

 (defun clean-file(filename) (your-function-goes-here)) (defun clean-each-dired-marked-file() (interactive) (for-each-dired-marked-file 'clean-file)) (defun for-each-dired-marked-file(fn) "Do stuff for each marked file, only works in dired window" (interactive) (if (eq major-mode 'dired-mode) (let ((filenames (dired-get-marked-files))) (mapcar fn filenames)) (error (format "Not a Dired buffer \(%s\)" major-mode)))) 
0
source share

All Articles