Emacs Indenting Revisited

Here’s a much simpler way to get emacs to behave nicely with ⌘-] and ⌘-[. Add the following to your .emacs, modifying the code to use the appropriate keymap for your build of emacs:

(define-key osx-key-mode-map (kbd "A-[")
(lambda () (interactive)
(indent-rigidly (region-beginning) (region-end) (- tab-width))
(setq mark-active t deactivate-mark nil)))
(define-key osx-key-mode-map (kbd "A-]")
(lambda () (interactive)
(indent-rigidly (region-beginning) (region-end) tab-width)
(setq mark-active t deactivate-mark nil)))

The key is the magic invocation of (setq mark-active t deactivate-mark nil) which ensures that, regardless of whether you’re using transient-mark-mode or not, the region will stay visibly highlighted after you’ve performed the indentation. It turns out that deactivate-mark is a defsubst designed to make this sort of thing easy on the developer. It even invokes the necessary hooks.