8

I want all tabs to be 4 spaces. I have the following in .emacs

(setq-default indent-tabs-mode nil)
(setq c-basic-indent 4)
(setq tab-width 4)

But this gets overwritten by some of the major mode themes that I can use. Is there a way to force this issue through my .emacs file?

nbro
  • 15,395
  • 32
  • 113
  • 196
David
  • 2,834
  • 6
  • 26
  • 31

3 Answers3

6

Try this to overwrite whatever any major mode overwrites:

(add-hook 'after-change-major-mode-hook 
          '(lambda () 
             (setq-default indent-tabs-mode nil)
             (setq c-basic-indent 4)
             (setq tab-width 4)))

Note though that major modes that aren't based on c-mode are not likely to care about c-basic-indent and may potentially use their own, mode-specific indentation variables. In such cases, there's no way around configuring these variables manually.

Thomas
  • 17,016
  • 4
  • 46
  • 70
2

Declare a default C indentation style, rather than declaring specific style parameters.

(setq c-default-style "k&r2")  ;; or whatever your preference is
(set-default 'indent-tabs-mode nil)
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
0

I "solved" this problem with a particularly ugly hack. Rather than try to figure out how to get the right major mode hooks in place, I just did the following:

(defun save-buffer-without-tabs ()
  (interactive)
  (untabify (point-min) (point-max))
  (save-buffer))
(global-set-key "\C-x\C-s" 'save-buffer-without-tabs)

This horribly breaks some things (that I care about, those things are Python and Makefiles). Thus, I also did the following:

;; restore the original save function for makefiles
(add-hook 'makefile-mode-hook
  (lambda ()
    (define-key makefile-mode-map "\C-x\C-s" 'save-buffer)))

;; restore the original save function for python files
(add-hook 'python-mode-hook
  (lambda () (define-key python-mode-map "\C-x\C-s" 'save-buffer)))

I wasn't aware of the after-change-major-mode-hook mentioned by Thomas, but if his solution doesn't work for you for some reason, I've been using this for a few years now without incident.

Edit: Upon closer inspection, I don't think you're asking exactly the question I answered. I guess nuking all the tabs is one way to get consistent indentation. :)

deong
  • 3,820
  • 21
  • 18