Skip to content Skip to sidebar Skip to footer

Set Python Indent To 2 Spaces In Emacs 23?

I am using emacs 23.1.1 on Ubuntu 10.04. I wish to program in Python with a 2-space indent. emacs looks to have a default mode for python (python.el?). I put the following in my .

Solution 1:

You can put this into your .emacs file:

(add-hook 'python-mode-hook '(lambda () 
 (setq python-indent 2)))

The reason why

    (setq-default python-indent 2)

does not work may because this variable does not exit when .emacs is loaded. (But I am an emacs newbie. I am not sure about my explanation.)

However, PEP 8 -- Style Guide for Python Code recommends "4 spaces per indentation level" and I find 4 spaces more readable. I actually use this piece of code to force a 4 spaces indentation.

Solution 2:

Either in you .emacs file or in a file referenced by your .emacs add:

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

You can put in a hook if you want to localize

;; Python Hook
(add-hook 'python-mode-hook
          (function (lambda ()
                      (setq indent-tabs-mode nil
                            tab-width 2))))

EDIT: I have found the following the following issues can mess with my settings:

  • setting the variable before the library is loaded
  • other packages/configs resetting the global variables

For both those issues I have found creating hooks and localizing the variables can help.

Solution 3:

I just ran into this problem myself, and I think the help for python-indent contains a big clue that no one else mentioned:

See also `M-x python-guess-indent'

If you don't customize python-guess-indent by setting it to nil, then python.el will automatically set python-indent for each Python buffer (that contains indented text), making your python-indent customization ineffective. (On the other hand, when in Rome...)

In the end, this is what went into my .emacs file (ignoring all other custom variables):

(custom-set-variables
 '(python-guess-indent nil)'(python-indent 2))

Post a Comment for "Set Python Indent To 2 Spaces In Emacs 23?"