Emacs global configuration of tabs

emacsexpandspacestabs

I'm attempting to switch from Vim to Emacs, but I'm tearing my hair out trying to configure it to treat tabs how I wish. I require:

  • Inserted "tabs" to be expanded into two spaces. Emacs stubbornly sticks to eight, no matter what I do.
  • Tabs (i.e. real \t characters) to be represented on screen by two spaces.
  • Pressing TAB should insert a tab at the cursor rather than indent the entire line. Currently, I press TAB anywhere and Emacs destroys all whitespace at the start of the line; this is the most infuriating thing so far.

My current ~/.emacs reads

(setq standard-indent 2)
(setq-default indent-tabs-mode nil)

but I have tried no end of suggested configurations from the web, none of which have done what they said they would. (Does the API constantly change? I'm using GNU Emacs 23.1.1, apparently.)

Best Answer

Emacs has extremely flexible support for handling indentation. Generally the mode that you are in dictates how they work - so if you're working on a C file then the way that pressing tab works will be different than if you're working on a Python file.

So it does depend which mode you're working in, which will limit the answers you get. In most cases I would recommend that you don't fight against it - for me the indentation behaviour is one of the best features of emacs. However, you do need to spend the time to customize it for yourself.

To change the way that tabs are displayed you need to set tab-width to 2. If you're editing Java or C style code then it sounds like you want to turn off all the nice indentation features by these to NIL:

  • c-tab-always-indent
  • c-syntactic-indentation
  • indent-tabs-mode

I suggest you set these through the customization interface. If you use "M-x customize-group RET C" then you can see the various settings for C mode.

If you're editting different types of files then the instructions will be different.

Perhaps emacs is in the wrong mode for your file. You could try doing "M-x fundamental-mode" to see if you prefer the behaviour there.