Emacs has a feature where it can automatically convert leading spaces to tabs. This is controlled by the indent-tabs-mode variable. I find mixing tabs and spaces extremely annoying as graphical diff tools will often display a tab and an equivalent number of spaces differently. Therefore I like to disable this behaviour. However, the obvious solution doesn’t work.
(setq indent-tabs-mode nil)
The documentation explains the reason
Its value is nil
Automatically becomes buffer-local when set in any fashion.
…
I’m surprised it works like this. Fortunately, there is a simple fix:
(customize-set-variable 'indent-tabs-mode nil)
If it wasn’t a customizable variable1 you might use something similar to the following.
(add-hook 'first-change-hook
(lambda () (setq indent-tabs-mode nil)))
Update: (setq-default ...)
looks like a better solution. Thanks to Ron for the tip.
(setq-default 'indent-tabs-mode nil)
1. Is this even possible for a variable that automatically becomes buffer-local when set?
(setq-default indent-tabs-mode nil) in .emacs ?
Works for me.
Thanks for the tip Ron. I’ve updated the post.
Any idea how to re-enable tabs from within emacs. I have (setq-default indent-tabs-mode nil) in my .emacs which is fine 98% of the time, but sometimes I actually need tabs which means quiting emacs, commenting out the line in my .emacs, editing the file, the uncommenting it in my .emacs when I’m done. Is there any way to temporarily disable it while within emacs? So far I’ve had no luck finding an answer with google.
Thanks.
Hi Cecil,
If you want a single tab character, use C-q <TAB>. If you want to re-enable it for new buffers, put (setq-default indent-tabs-mode t) in the *scratch* buffer and the do C-x C-e to execute it. Or you could use M-x eval-expression instead. Let me know if that works for you.
Hello Jared:
I don’t know where were my manners! I came back to your post via a google search today. I don’t know why I didn’t reply to your suggestion, but thanks, it works, and all the best for the new year!
Thanks
It works
just what I need
But when I press a ,it goes right few space blocks
then I press
I hope emacs will delete the whole tab block,not just delete one space by one .
I like this behavior, really, in VIM
Can anybody tell how to do it with .emacs?
FWIW setq-default did not work for me (emacs on windows). set-default usually works fine on all my UNIX emacses.
The set-hook idea helped me, ’cause I want to keep tabs as default but eliminate them in C/C++/Java code:
;; set the buffer-local variable indent-tabs-mode to nil, in C and C++
(add-hook ‘c-mode-common-hook (lambda () (setq indent-tabs-mode nil)))