I'm using the Python REPL in a comint window via the run-python command, and I'm seeing bad behavior when I use the TAB key to do my indentation. For example:

>>> for i in range(3):
...     print(i)
  File "<stdin>", line 2
IndentationError: expected an indented block

Here, the indentation before print was created using TAB. I use TAB when editing normal Python buffers, and it inserts 4 spaces in those cases. Here it seems to be inserting an actual TAB and it results in an IndentationError.

I'd like it if TAB would just insert 4 spaces. I'm sure this is something really simple, but it's eluding me. Anyone know what I'm doing wrong?

  • This does not reproduce for me. Does it reproduce for you in emacs -Q?
    – PythonNut
    Feb 10, 2015 at 19:43
  • No, it doesn't reproduce with -Q. I'm sure (as you've confirmed) that it's something in my config, but I'm too brain-tired right now to make an effective stab at tracking down the right setting. I guess a more concrete question is: What variable - if any - controls what TAB does in the REPL?
    – abingham
    Feb 10, 2015 at 20:02
  • I see... What does C-h k TAB say? It should lead you to python-shell-completion-complete-or-indent. That, in turn calls indent-for-tab-command, which is part of the regular emacs indentation code.
    – PythonNut
    Feb 10, 2015 at 20:06
  • C-h k TAB is actually bound to yas-expand. However, if I run either python-shell-completion-complete-or-indent or indent-for-tab-command directly to insert the indentation, I still get the odd behavior.
    – abingham
    Feb 10, 2015 at 21:08
  • Try M-: (setq tab-width 4 indent-tabs-mode nil) RET in the python buffer.
    – PythonNut
    Feb 10, 2015 at 21:13

1 Answer 1


Hm... Let me make this an answer.

TAB in a Python REPL triggers yas-expand in your case. This in turn calls python-shell-completion-complete-or-indent, which calls indent-for-tab-command. This is controlled by the regular Emacs indentation variables, which are buffer local. To fix this, you can do the following:

(add-hook 'inferior-python-mode-hook
  (lambda ()
      indent-tabs-mode nil ;; i.e. indent with spaces
      tab-width 4          ;; i.e. tabs consts of 4 spaces
  • I was wondering if you'd answer ;) That's exactly the hook I created as well.
    – abingham
    Feb 12, 2015 at 5:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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