Reputation: 206
I'm currently working in Java with a team. Whenever we share files, their files are always indented weirdly on my computer, and I have to either tab through them all or C-x h C-M-.
Is there a way to make it so that emacs will automatically format (auto-tab the whole file) whenever I open the file, so I don't have to enter that macro every time?
Thank you very much!
Upvotes: 1
Views: 724
Reputation: 41
I have experienced similar problems when working in emacs alongside non-emacs coders. I was seeing "weirdness" due to emacs' default tab indention being set to 8 columns instead of 4. Setting your tab width to 4 should fix this. You can enter M-x whitespace-mode to look at your whitespace characters and see if that's the problem. If so, you can add the following to your init file to fix it:
(setq-default tab-width 4) ;; emacs version 23.2+
(setq default-tab-width 4) ;; emacs versions prior to 23.2
When I need to re-indent a file, I call the following function from my init file with M-x iwb:
(defun iwb ()
"indent whole buffer"
(interactive)
(delete-trailing-whitespace)
(indent-region (point-min) (point-max))
(untabify (point-min) (point-max)))
A hook could be added for this function similar to Wintermute's reponse.
(add-hook 'java-mode-hook #'iwb)
Upvotes: 1
Reputation: 44063
Put this in your ~/.emacs:
(add-hook 'java-mode-hook (lambda () (indent-region (point-min) (point-max))))
This registers a function to be executed when the Java major mode is entered, and that function is a lambda expression that indents the region between (point-min)
and (point-max)
-- i.e., the entire buffer.
It will be loaded the next time you start emacs. To get it into the running session, put the cursor behind it and press C-x C-e.
Upvotes: 3