In Python mode (python.el), I am in the habit of hitting C-j to return and indent properly. However, when I am in an inferior python buffer, this command only inserts a newline and does not indent. Is there any way to get the inferior-python-mode to work more like python-mode in this respect, or maybe even set up auto-indent the way it normally works in ipython? I have read through the documentation for inferior-python-mode, but can't find anything useful. I love using Emacs for Python, but there are a few pain points, and I am having trouble finding good documentation. Thanks in advance for any advice!
1 Answer
The problem is that newline-and-indent (the function that C-j is bound to) inserts a literal newline then whatever would be inserted by TAB. What you want is to send the current input:
(defun send-input-and-indent ()
(interactive)
(comint-send-input)
(indent-for-tab-command))
Next, bind send-input-and-indent to C-j only when in inferior-python-mode:
(define-key inferior-python-mode-map (kbd "C-j") 'send-input-and-indent)
Put both snippets in your initialization file and you're good to go.
-
Nah - that only works if you press it at the end of a line, and even then the indentation settings from
python-modeare not obeyed. But, for example if you havedef f(a=1,^ b=2):and the cursor is at position^, it will produce rubbish that can only be stopped withC-c C-c.Christian Herenz– Christian Herenz2025-08-21 11:49:01 +00:00Commented Aug 21 at 11:49 -
Also note
C-jis bound to'electric-newline-and-maybe-indentininferior-python-mode.Christian Herenz– Christian Herenz2025-08-21 12:10:43 +00:00Commented Aug 21 at 12:10