Indenting code is very important, even if you are not programming in Python. It makes the structure of the code much clearer if everything is properly indented. Most editors nowadays will properly indent your code for you, and emacs is no exception. Most of the following customizations were gotten from the emacs-wiki page on autoindentation.
The first set of utilities is advice for yank and yank-pop to indent whatever they just pasted. This is useful if, for example, you copy some code from another file at a different indentation level than you want to paste it at. With these advice, the code will be indented properly relative to wherever you paste it.
(defadvice yank (after indent-region activate) (if (member major-mode '(emacs-lisp-mode scheme-mode lisp-mode c-mode c++-mode objc-mode latex-mode plain-tex-mode)) (let ((mark-even-if-inactive t)) (indent-region (region-beginning) (region-end) nil)))) (defadvice yank-pop (after indent-region activate) (if (member major-mode '(emacs-lisp-mode scheme-mode lisp-mode c-mode c++-mode objc-mode latex-mode plain-tex-mode)) (let ((mark-even-if-inactive t)) (indent-region (region-beginning) (region-end) nil))))
The next function, also from the emacs-wiki, is a replacement for kill-line. Normally, if you kill a newline and the next line is indented, you will have to execute just-one-space or something similar to get rid of all the extra indentation. This will do that automatically for you, saving some time. I just rebind it to C-k, overriding kill-line, since this is almost always the behavior I want.
(defun kill-and-join-forward (&optional arg) "If at end of line, join with following; otherwise kill line. Deletes whitespace at join." (interactive "P") (if (and (eolp) (not (bolp))) (delete-indentation t) (kill-line arg))) (global-set-key (kbd "C-k") 'kill-and-join-forward)
The last customization I have is a keybinding for a function that is already pretty accessible. C-j will perform a newline and indent, but I often just use the return key instead and then have to indent myself(admittedly, only a tab character, but it’s still annoying). Since the times I’ve needed to just insert a newline without indenting are very rare, I just set RET to newline-and-indent. The other option I considered was binding RET to indent-new-comment-line, but after trying that for a while I decided I preffered newline-and-indent.
(global-set-key (kbd "RET") 'newline-and-indent)