2
votes

Emacs tab indentation in python mode is using tab instead of 4-spaces.

My emacs init.el file contains:

(setq-default indent-tabs-mode t)
(setq-default tab-width 4)
(setq indent-line-function 'insert-tab)

I have tried:

(setq-default indent-tabs-mode nil)

but it didn't make any difference. Using white-space mode in emacs I see that tab does NOT indent 4-white-spaces and untabify fixes the tab to 4-white-spaces. How do I make TAB to work as four white-spaces?

UPDATE fixed by changing init.el config to:

(add-hook 'python-mode-hook
      (lambda ()
        (setq-default indent-tabs-mode nil)
        (setq-default tab-width 4)
        (setq-default python-indent 4)))
2

2 Answers

2
votes

If you want to insert TABs, indent-tabs-mode must be `t'. Change that in hook shown. Write

(setq indent-tabs-mode t)

Seems python.el has a bug, when setting it to nil alongside with mode. As hooks run after the mode init, it should be able to correct that.

If not, try python-mode.el, which permits choice. Also you can set indent-tabs-mode, which is made buffer-local by python.el, in every buffer explicitly.

2
votes

Though it's late, following hooks worked for me. Only spaces

(add-hook 'python-mode-hook
      (lambda ()
        (setq indent-tabs-mode nil)
        (setq python-indent 4)
        (setq tab-width 4))
      (untabify (point-min) (point-max)))

Only tabs

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