Auto-formatting a source file in emacs

Open the file and then indent it by indenting the entire region:

M-x find-file /path/to/file RET
C-x h                             (M-x mark-whole-buffer)
C-M-\                             (M-x indent-region)

Now, it looks like you're trying to apply C indentation to a buffer that's not in C mode. To get it into C mode

M-x c-mode

Or c++-mode, or whatever mode you want. But, since it's assembler code, you probably want assembler mode (which Emacs will do by default for .s files). In which case, the indentation command above (C-M-\ is also known as M-x indent-region) should work for you.

Note: the command sequence at the top can be rolled into a single command like this:

(defun indent-file (file)
  "prompt for a file and indent it according to its major mode"
  (interactive "fWhich file do you want to indent: ")
  (find-file file)
  ;; uncomment the next line to force the buffer into a c-mode
  ;; (c-mode)
  (indent-region (point-min) (point-max)))

And, if you want to learn how to associate major-modes with files based on extensions, check out the documentation for auto-mode-alist. To be fair, it's not necessarily extension based, just regular expressions matched against the filename.


Try M-x asm-mode. That will switch to assembler mode. Not sure how it will go with assembler embedded in the middle of a C file.