2

I just installed python-mode from ELPA and when I hit Enter the cursor goes straight to the beginning of the next line. For instance for the following code:

def hello_world():
    print "hello world!"
    for i in range(3):
        print "hello again"
    return 0

I have to hit TAB after Enter every time after I hit Enter to go to a new-line (although interestingly TAB sends the cursor to the right place).

When I installed python-mode I got some warning messages relating to indentation which I don't really understand, here is a link to those warning messages.

Mike Vella
  • 10,187
  • 14
  • 59
  • 86

3 Answers3

4

C-j is the key I was looking for ('newline-and-indent' command). I managed to rebind Enter to this by putting the following hook in my init.el:

(add-hook 'python-mode-hook
          (lambda ()
             (define-key python-mode-map "\r" 'newline-and-indent)))
Mike Vella
  • 10,187
  • 14
  • 59
  • 86
  • 2
    just for people copy-pasting the piece of code from here: it's missing one ')' from the end, which makes emacs complain about malformed init file. – J.Nieminen Nov 06 '13 at 15:02
3

Not sure why you installed python-mode, since Emacs comes with Python support built-in, but I don't think this affects the rest. If you want RET to indent after inserting a the newline, you probably like that everywhere, so you might like to enable electric-indent-mode.

Stefan
  • 27,908
  • 4
  • 53
  • 82
2

Try using C-j instead of enter.

Actually, C-j is bound to (newline-and-indent), which does the two steps(enter and tab)mentioned in the question.

As of version 24.4.50.1 the default behavior has been reversed i.e enter adds newline and indent if needed while C-j doesn't. Although the functions these key-bindings map to aren't as mentioned above.

Bleeding Fingers
  • 6,993
  • 7
  • 46
  • 74
  • @MikeVella if enter did what C-j does i would find that kind of awkward. although it was otherwise at first but later on seemed logically to me. – Bleeding Fingers Aug 15 '13 at 21:20
  • OK, I found a discussion about C-j does in the source code. Now I'm going to try and rebind RET to C-j. – Mike Vella Aug 15 '13 at 21:21
  • @MikeVella I suggest you make a habit of using `C-j` for the purpose, because that way you wouldn't be a searching for a key that gives you an indentation-free-newline, having to use `M-x newline` and other not-so-simple ways of doing so. – Bleeding Fingers Aug 15 '13 at 21:39
  • @hus784 'newline-and-indent' does a really good job of guessing which line of indentation I want (e.g indenting after a : but not after a print statement") So I'm happy to rebind RET to that. – Mike Vella Aug 15 '13 at 21:43