views:

1500

answers:

4

How do I apply a set of formatting rules to an existing source file in emacs?

Specifically I have an assembly (*.s) file, but I would like a generic command for all types of files.

I am trying to use M-x c-set-style with gnu style, but I am getting an error:

Buffer *.s is not a CC Mode buffer (c-set-style)

+1  A: 

emacs will use the file name extension to identify the mode, you should add some assemble language mode style in your custom.el file

cppguy
+5  A: 

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.

pgs
+14  A: 

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.

Trey Jackson
Best with emacs questions to note what the keystrokes bind to. I.e. `M-<` is usually bound to `beginning-of-buffer`. Use `C-h k` for keystroke help.
dmckee
Also, `C-x h' (mark-whole-buffer) selects everything in slightly fewer steps, and works even if you are using transient-mark-mode.
Jouni K. Seppänen
@Jouni, thanks for C-x h, I didn't know about that. incorporated the solution.
Trey Jackson
A: 

The major mode it's using for your .s files won't be cc-mode hence c-set-style makes no sense. However you can always manually enter cc-mode (M-x cc-mode) and then do the c-set-style you want. However as the C styles are keyed for C source code and not assembler this is almost certainly not what you want to do.

stsquad