3

I'd like tab-width to be set to 2 in all programming modes. I use prelude (which might be one of the problems), but I have this in my custom.el (which is sort of the analogue to .emacs):

(setq my-tab-width 2)
(setq standard-indent my-tab-width)
(setq tab-width my-tab-width)
(setq c-basic-offset my-tab-width)
(setq js2-basic-offset my-tab-width)
(setq web-mode-attr-indent-offset my-tab-width)
(setq web-mode-code-indent-offset my-tab-width)
(setq web-mode-css-indent-offset my-tab-width)

How can I avoid all the duplication?

  • If you want to set the **default** value of `tab-width` **everywhere**, use `setq-default`. If you want to set the value of `tab-width` in all modes that inherit from **`prog-mode`** then do what @dan suggested. – Drew Jan 12 '16 at 02:09
  • @Drew: Oops, I didn't mean to write `'(` but `(setq` instead. I'll change that. – Son of the Wai-Pan Jan 12 '16 at 06:10

1 Answers1

3

(Nearly) all programming modes inherit from prog-mode, so you can set the variable in prog-mode-hook:

(defun my-prog-mode-hook ()
  (setq tab-width 2))
(add-hook 'prog-mode-hook #'my-prog-mode-hook)

(Note that you could use a lambda instead, but this way you'll have an easier time removing the hook if you ever want to do so.)

Dan
  • 32,584
  • 6
  • 98
  • 168
  • Can you explain the `#'my-prog-mode-hook)` syntax? Thanks! – Son of the Wai-Pan Jan 12 '16 at 06:13
  • @Avery: see [get in the habit of using sharp quote](http://endlessparentheses.com/get-in-the-habit-of-using-sharp-quote.html), or check out the manual for more details. – Dan Jan 12 '16 at 19:34