简体   繁体   中英

How do I auto-indent in emacs when opening a file?

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 Cx h CM-.

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!

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) -- ie, 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 Cx Ce.

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 Mx 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 Mx 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM