Nick Bolton
Nick Bolton

Reputation: 39610

How do I set Emacs tab size to 4 chars wide for .py files?

I've tried using the following:

(setq-default tab-width 4)
(setq-default tab-stop-list (list 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60))

But the size of tabs when editing .py files is still 8 chars wide. In other files it has gone down to 4, so I assume the Python major mode is overriding this somehow. I see that I can set python-indent to 4, but this causes spaces to be inserted (which goes against our code style guide).

How do I make the tabs 4 chars in width?

Update:

I've also tried this, but it didn't do anything:

(add-hook 'python-mode-hook
  (setq indent-tabs-mode t)
  (setq tab-width 4)
)

Upvotes: 29

Views: 23731

Answers (4)

Tao Peng
Tao Peng

Reputation: 2718

(add-hook 'python-mode-hook
      (lambda ()
        (setq indent-tabs-mode t)
        (setq tab-width 4)
        (setq python-indent-offset 4)))

Upvotes: 53

nmichaels
nmichaels

Reputation: 50999

(setq indent-tabs-mode t)
(setq python-indent-offset 4)

Upvotes: 0

Trey Jackson
Trey Jackson

Reputation: 74470

The correct form for the hook is this:

(add-hook 'python-mode-hook
          (lambda ()
            (setq indent-tabs-mode t)
            (setq tab-width 4)))

You need to put the imperative statements inside a function (lambda).

Upvotes: 2

T.E.D.
T.E.D.

Reputation: 44804

I've had that same issue, but with C++ files. What finally did it for me was the following in my .emacs.

(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(c-basic-offset 4 t)
)

Actually of course I set it from the C++ mode area of the Customize Emacs menu, but this was the result. I'd see if python mode has something similar. py-basic-offset or something? Surf around the mode settings for pyton.

Upvotes: 0

Related Questions