Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to re-format 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 my source files at once, so that they are all formatted and indented correctly according to the Google style?

like image 306
Frank Avatar asked Apr 04 '09 14:04

Frank


2 Answers

There are several pieces to this:

  • you need to come up with EMACS functions to do all the reformatting you want. indent-region is a start, but you might also want to untabify or some other things.
  • you need to invoke them on each file, and since the indent functions work on ranges, you need a function that sets mark to cover the whole file: mark-whole-buffer.
  • you need to invoke EMACS on each file: this means invoking emacs with the --batch file.

There's a couple of nice blog posts on doing this here and here.

like image 65
Charlie Martin Avatar answered Oct 03 '22 20:10

Charlie Martin


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

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

Now you can run this on a buffer by typing C-x e. If you have loaded several files you can run something like C-u 100 C-x e to run this on 100 files. If this is more than the number of files, that is ok, you'll just get some "bell ring" or other error you can ignore once all the processing is complete.

like image 42
Alex B Avatar answered Oct 03 '22 20:10

Alex B