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 2:09
  • @Drew: Oops, I didn't mean to write '( but (setq instead. I'll change that. – Avery Jan 12 '16 at 6:10

(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.)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.