Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a very simple thing I want to do in Emacs. I want to set it so that when I press the TAB key, it inserts two spaces. Just this. It's all I ask. I have tried doing this for a couple of years now, and there's just no way to do it. In every file type it blows up in a different way. HTML file? Random choice between getting four spaces or tabbing to previous line indent. Python file? Just four spaces and I'll ignore any setting you have. It also randomly seems to stop working depending on the phase of the moon when it was previously working.

In my .emacs:

(setq indent-tabs-mode nil)
(setq tab-width 2)

This should work, right? No. No it doesn't. It seems emacs has a magical fairy "file mode" for each extension that completely overrides what I tell it. So do I have to find this magical fairy configuration and override it for each file type? What can I do to get this simple thing to work. Halp.

share|improve this question
add comment

1 Answer 1

up vote 4 down vote accepted

Each language has its own indentation convention, so it's not very useful to have the same effect from the easily-accessible Tab key all the time. That's why many major modes¹ override the key's binding.

To override the setting for a particular mode, bind it in its keymap.

(defun insert-two-spaces (&optional count)
  (interactive "*p")
  (insert (make-string (* 2 count) ?\ )))
(add-hook 'python-mode-hook '(local-set-key "\t" 'insert-two-spaces))

To override the setting everywhere, you can define an always-on minor mode. See the Elisp manual for how to define a minor mode.

(define-minor-mode magnus-minor-mode
  "Override the binding of the TAB key."
  :keymap '(([?\t] . insert-two-spaces))
  :global t)
(magnus-minor-mode 1)

¹ What you call “magical fairy file mode” is a major mode. If you don't like an editor that does things automatically, I suggest nano.

share|improve this answer
    
Just inserted this in my .emacs and tried editing a PHP file. Pressing tab, it inserts eight spaces and when I press backspace it highlights the spaces with a blinking block (wtf?). So still no go. Then again, it is a full moon. –  Magnus Oct 14 '12 at 21:56
    
@Magnus I forgot to turn on the minor mode. Does it help? If not, what does C-h c TAB show? –  Gilles Oct 14 '12 at 21:58
1  
Wow, yes that works. What was missing was the (magnus-minor-mode 1). I've tried it and it seems to be working with PHP, Python and Bash files so far. I shall evaluate further and wait for the phase of the moon to change before making my final judgement. –  Magnus Oct 14 '12 at 22:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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