Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-formatting a source file in emacs

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)

like image 589
Yuval Adam Avatar asked Jun 14 '09 11:06

Yuval Adam


4 Answers

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.

like image 163
Trey Jackson Avatar answered Nov 17 '22 20:11

Trey Jackson


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.

like image 36
pgs Avatar answered Nov 17 '22 19:11

pgs


if you want indent current buffer

(defun iwb ()
  "indent whole buffer"
  (interactive)
  (delete-trailing-whitespace)
  (indent-region (point-min) (point-max) nil)
  (untabify (point-min) (point-max)))
like image 3
user1990 Avatar answered Nov 17 '22 21:11

user1990


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

like image 1
cppguy Avatar answered Nov 17 '22 21:11

cppguy